• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "src/objects/string-comparator.h"
6 
7 #include "src/objects/string-inl.h"
8 
9 namespace v8 {
10 namespace internal {
11 
Init(String string)12 void StringComparator::State::Init(String string) {
13   ConsString cons_string = String::VisitFlat(this, string);
14   iter_.Reset(cons_string);
15   if (!cons_string.is_null()) {
16     int offset;
17     string = iter_.Next(&offset);
18     String::VisitFlat(this, string, offset);
19   }
20 }
21 
Advance(int consumed)22 void StringComparator::State::Advance(int consumed) {
23   DCHECK(consumed <= length_);
24   // Still in buffer.
25   if (length_ != consumed) {
26     if (is_one_byte_) {
27       buffer8_ += consumed;
28     } else {
29       buffer16_ += consumed;
30     }
31     length_ -= consumed;
32     return;
33   }
34   // Advance state.
35   int offset;
36   String next = iter_.Next(&offset);
37   DCHECK_EQ(0, offset);
38   DCHECK(!next.is_null());
39   String::VisitFlat(this, next);
40 }
41 
Equals(String string_1,String string_2)42 bool StringComparator::Equals(String string_1, String string_2) {
43   int length = string_1.length();
44   state_1_.Init(string_1);
45   state_2_.Init(string_2);
46   while (true) {
47     int to_check = std::min(state_1_.length_, state_2_.length_);
48     DCHECK(to_check > 0 && to_check <= length);
49     bool is_equal;
50     if (state_1_.is_one_byte_) {
51       if (state_2_.is_one_byte_) {
52         is_equal = Equals<uint8_t, uint8_t>(&state_1_, &state_2_, to_check);
53       } else {
54         is_equal = Equals<uint8_t, uint16_t>(&state_1_, &state_2_, to_check);
55       }
56     } else {
57       if (state_2_.is_one_byte_) {
58         is_equal = Equals<uint16_t, uint8_t>(&state_1_, &state_2_, to_check);
59       } else {
60         is_equal = Equals<uint16_t, uint16_t>(&state_1_, &state_2_, to_check);
61       }
62     }
63     // Looping done.
64     if (!is_equal) return false;
65     length -= to_check;
66     // Exit condition. Strings are equal.
67     if (length == 0) return true;
68     state_1_.Advance(to_check);
69     state_2_.Advance(to_check);
70   }
71 }
72 
73 }  // namespace internal
74 }  // namespace v8
75