1 // Copyright 2014 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 #ifndef V8_STRINGS_STRING_BUILDER_INL_H_
6 #define V8_STRINGS_STRING_BUILDER_INL_H_
7
8 #include "src/common/assert-scope.h"
9 #include "src/execution/isolate.h"
10 #include "src/handles/handles-inl.h"
11 #include "src/heap/factory.h"
12 #include "src/objects/fixed-array.h"
13 #include "src/objects/objects.h"
14 #include "src/objects/string-inl.h"
15 #include "src/utils/utils.h"
16
17 namespace v8 {
18 namespace internal {
19
20 const int kStringBuilderConcatHelperLengthBits = 11;
21 const int kStringBuilderConcatHelperPositionBits = 19;
22
23 using StringBuilderSubstringLength =
24 base::BitField<int, 0, kStringBuilderConcatHelperLengthBits>;
25 using StringBuilderSubstringPosition =
26 base::BitField<int, kStringBuilderConcatHelperLengthBits,
27 kStringBuilderConcatHelperPositionBits>;
28
29 template <typename sinkchar>
30 void StringBuilderConcatHelper(String special, sinkchar* sink,
31 FixedArray fixed_array, int array_length);
32
33 // Returns the result length of the concatenation.
34 // On illegal argument, -1 is returned.
35 int StringBuilderConcatLength(int special_length, FixedArray fixed_array,
36 int array_length, bool* one_byte);
37
38 class FixedArrayBuilder {
39 public:
40 explicit FixedArrayBuilder(Isolate* isolate, int initial_capacity);
41 explicit FixedArrayBuilder(Handle<FixedArray> backing_store);
42
43 bool HasCapacity(int elements);
44 void EnsureCapacity(Isolate* isolate, int elements);
45
46 void Add(Object value);
47 void Add(Smi value);
48
array()49 Handle<FixedArray> array() { return array_; }
50
length()51 int length() { return length_; }
52
53 int capacity();
54
55 Handle<JSArray> ToJSArray(Handle<JSArray> target_array);
56
57 private:
58 Handle<FixedArray> array_;
59 int length_;
60 bool has_non_smi_elements_;
61 };
62
63 class ReplacementStringBuilder {
64 public:
65 ReplacementStringBuilder(Heap* heap, Handle<String> subject,
66 int estimated_part_count);
67
68 // Caution: Callers must ensure the builder has enough capacity.
AddSubjectSlice(FixedArrayBuilder * builder,int from,int to)69 static inline void AddSubjectSlice(FixedArrayBuilder* builder, int from,
70 int to) {
71 DCHECK_GE(from, 0);
72 int length = to - from;
73 DCHECK_GT(length, 0);
74 if (StringBuilderSubstringLength::is_valid(length) &&
75 StringBuilderSubstringPosition::is_valid(from)) {
76 int encoded_slice = StringBuilderSubstringLength::encode(length) |
77 StringBuilderSubstringPosition::encode(from);
78 builder->Add(Smi::FromInt(encoded_slice));
79 } else {
80 // Otherwise encode as two smis.
81 builder->Add(Smi::FromInt(-length));
82 builder->Add(Smi::FromInt(from));
83 }
84 }
85
AddSubjectSlice(int from,int to)86 void AddSubjectSlice(int from, int to) {
87 EnsureCapacity(2); // Subject slices are encoded with up to two smis.
88 AddSubjectSlice(&array_builder_, from, to);
89 IncrementCharacterCount(to - from);
90 }
91
92 void AddString(Handle<String> string);
93
94 MaybeHandle<String> ToString();
95
IncrementCharacterCount(int by)96 void IncrementCharacterCount(int by) {
97 if (character_count_ > String::kMaxLength - by) {
98 STATIC_ASSERT(String::kMaxLength < kMaxInt);
99 character_count_ = kMaxInt;
100 } else {
101 character_count_ += by;
102 }
103 }
104
105 private:
106 void AddElement(Handle<Object> element);
107 void EnsureCapacity(int elements);
108
109 Heap* heap_;
110 FixedArrayBuilder array_builder_;
111 Handle<String> subject_;
112 int character_count_;
113 bool is_one_byte_;
114 };
115
116 class IncrementalStringBuilder {
117 public:
118 explicit IncrementalStringBuilder(Isolate* isolate);
119
CurrentEncoding()120 V8_INLINE String::Encoding CurrentEncoding() { return encoding_; }
121
122 template <typename SrcChar, typename DestChar>
123 V8_INLINE void Append(SrcChar c);
124
AppendCharacter(uint8_t c)125 V8_INLINE void AppendCharacter(uint8_t c) {
126 if (encoding_ == String::ONE_BYTE_ENCODING) {
127 Append<uint8_t, uint8_t>(c);
128 } else {
129 Append<uint8_t, uc16>(c);
130 }
131 }
132
AppendCString(const char * s)133 V8_INLINE void AppendCString(const char* s) {
134 const uint8_t* u = reinterpret_cast<const uint8_t*>(s);
135 if (encoding_ == String::ONE_BYTE_ENCODING) {
136 while (*u != '\0') Append<uint8_t, uint8_t>(*(u++));
137 } else {
138 while (*u != '\0') Append<uint8_t, uc16>(*(u++));
139 }
140 }
141
AppendCString(const uc16 * s)142 V8_INLINE void AppendCString(const uc16* s) {
143 if (encoding_ == String::ONE_BYTE_ENCODING) {
144 while (*s != '\0') Append<uc16, uint8_t>(*(s++));
145 } else {
146 while (*s != '\0') Append<uc16, uc16>(*(s++));
147 }
148 }
149
AppendInt(int i)150 V8_INLINE void AppendInt(int i) {
151 char buffer[kIntToCStringBufferSize];
152 const char* str =
153 IntToCString(i, Vector<char>(buffer, kIntToCStringBufferSize));
154 AppendCString(str);
155 }
156
CurrentPartCanFit(int length)157 V8_INLINE bool CurrentPartCanFit(int length) {
158 return part_length_ - current_index_ > length;
159 }
160
161 // We make a rough estimate to find out if the current string can be
162 // serialized without allocating a new string part. The worst case length of
163 // an escaped character is 6. Shifting the remaining string length right by 3
164 // is a more pessimistic estimate, but faster to calculate.
EscapedLengthIfCurrentPartFits(int length)165 V8_INLINE int EscapedLengthIfCurrentPartFits(int length) {
166 if (length > kMaxPartLength) return 0;
167 STATIC_ASSERT((kMaxPartLength << 3) <= String::kMaxLength);
168 // This shift will not overflow because length is already less than the
169 // maximum part length.
170 int worst_case_length = length << 3;
171 return CurrentPartCanFit(worst_case_length) ? worst_case_length : 0;
172 }
173
174 void AppendString(Handle<String> string);
175
176 MaybeHandle<String> Finish();
177
HasOverflowed()178 V8_INLINE bool HasOverflowed() const { return overflowed_; }
179
180 int Length() const;
181
182 // Change encoding to two-byte.
ChangeEncoding()183 void ChangeEncoding() {
184 DCHECK_EQ(String::ONE_BYTE_ENCODING, encoding_);
185 ShrinkCurrentPart();
186 encoding_ = String::TWO_BYTE_ENCODING;
187 Extend();
188 }
189
190 template <typename DestChar>
191 class NoExtend {
192 public:
NoExtend(Handle<String> string,int offset,const DisallowHeapAllocation & no_gc)193 NoExtend(Handle<String> string, int offset,
194 const DisallowHeapAllocation& no_gc) {
195 DCHECK(string->IsSeqOneByteString() || string->IsSeqTwoByteString());
196 if (sizeof(DestChar) == 1) {
197 start_ = reinterpret_cast<DestChar*>(
198 Handle<SeqOneByteString>::cast(string)->GetChars(no_gc) + offset);
199 } else {
200 start_ = reinterpret_cast<DestChar*>(
201 Handle<SeqTwoByteString>::cast(string)->GetChars(no_gc) + offset);
202 }
203 cursor_ = start_;
204 }
205
Append(DestChar c)206 V8_INLINE void Append(DestChar c) { *(cursor_++) = c; }
AppendCString(const char * s)207 V8_INLINE void AppendCString(const char* s) {
208 const uint8_t* u = reinterpret_cast<const uint8_t*>(s);
209 while (*u != '\0') Append(*(u++));
210 }
211
written()212 int written() { return static_cast<int>(cursor_ - start_); }
213
214 private:
215 DestChar* start_;
216 DestChar* cursor_;
217 DISALLOW_HEAP_ALLOCATION(no_gc_)
218 };
219
220 template <typename DestChar>
221 class NoExtendString : public NoExtend<DestChar> {
222 public:
NoExtendString(Handle<String> string,int required_length)223 NoExtendString(Handle<String> string, int required_length)
224 : NoExtend<DestChar>(string, 0), string_(string) {
225 DCHECK(string->length() >= required_length);
226 }
227
Finalize()228 Handle<String> Finalize() {
229 Handle<SeqString> string = Handle<SeqString>::cast(string_);
230 int length = NoExtend<DestChar>::written();
231 Handle<String> result = SeqString::Truncate(string, length);
232 string_ = Handle<String>();
233 return result;
234 }
235
236 private:
237 Handle<String> string_;
238 };
239
240 template <typename DestChar>
241 class NoExtendBuilder : public NoExtend<DestChar> {
242 public:
NoExtendBuilder(IncrementalStringBuilder * builder,int required_length,const DisallowHeapAllocation & no_gc)243 NoExtendBuilder(IncrementalStringBuilder* builder, int required_length,
244 const DisallowHeapAllocation& no_gc)
245 : NoExtend<DestChar>(builder->current_part(), builder->current_index_,
246 no_gc),
247 builder_(builder) {
248 DCHECK(builder->CurrentPartCanFit(required_length));
249 }
250
~NoExtendBuilder()251 ~NoExtendBuilder() {
252 builder_->current_index_ += NoExtend<DestChar>::written();
253 }
254
255 private:
256 IncrementalStringBuilder* builder_;
257 };
258
259 private:
factory()260 Factory* factory() { return isolate_->factory(); }
261
accumulator()262 V8_INLINE Handle<String> accumulator() { return accumulator_; }
263
set_accumulator(Handle<String> string)264 V8_INLINE void set_accumulator(Handle<String> string) {
265 accumulator_.PatchValue(*string);
266 }
267
current_part()268 V8_INLINE Handle<String> current_part() { return current_part_; }
269
set_current_part(Handle<String> string)270 V8_INLINE void set_current_part(Handle<String> string) {
271 current_part_.PatchValue(*string);
272 }
273
274 // Add the current part to the accumulator.
275 void Accumulate(Handle<String> new_part);
276
277 // Finish the current part and allocate a new part.
278 void Extend();
279
280 // Shrink current part to the right size.
ShrinkCurrentPart()281 void ShrinkCurrentPart() {
282 DCHECK(current_index_ < part_length_);
283 set_current_part(SeqString::Truncate(
284 Handle<SeqString>::cast(current_part()), current_index_));
285 }
286
287 void AppendStringByCopy(Handle<String> string);
288 bool CanAppendByCopy(Handle<String> string);
289
290 static const int kInitialPartLength = 32;
291 static const int kMaxPartLength = 16 * 1024;
292 static const int kPartLengthGrowthFactor = 2;
293 static const int kIntToCStringBufferSize = 100;
294
295 Isolate* isolate_;
296 String::Encoding encoding_;
297 bool overflowed_;
298 int part_length_;
299 int current_index_;
300 Handle<String> accumulator_;
301 Handle<String> current_part_;
302 };
303
304 template <typename SrcChar, typename DestChar>
Append(SrcChar c)305 void IncrementalStringBuilder::Append(SrcChar c) {
306 DCHECK_EQ(encoding_ == String::ONE_BYTE_ENCODING, sizeof(DestChar) == 1);
307 if (sizeof(DestChar) == 1) {
308 DCHECK_EQ(String::ONE_BYTE_ENCODING, encoding_);
309 SeqOneByteString::cast(*current_part_)
310 .SeqOneByteStringSet(current_index_++, c);
311 } else {
312 DCHECK_EQ(String::TWO_BYTE_ENCODING, encoding_);
313 SeqTwoByteString::cast(*current_part_)
314 .SeqTwoByteStringSet(current_index_++, c);
315 }
316 if (current_index_ == part_length_) Extend();
317 }
318 } // namespace internal
319 } // namespace v8
320
321 #endif // V8_STRINGS_STRING_BUILDER_INL_H_
322