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 #include "src/execution/arguments-inl.h"
6 #include "src/heap/heap-inl.h"
7 #include "src/logging/counters.h"
8 #include "src/numbers/conversions.h"
9 #include "src/objects/js-array-inl.h"
10 #include "src/objects/objects-inl.h"
11 #include "src/objects/slots.h"
12 #include "src/objects/smi.h"
13 #include "src/regexp/regexp-utils.h"
14 #include "src/runtime/runtime-utils.h"
15 #include "src/strings/string-builder-inl.h"
16 #include "src/strings/string-search.h"
17
18 namespace v8 {
19 namespace internal {
20
RUNTIME_FUNCTION(Runtime_GetSubstitution)21 RUNTIME_FUNCTION(Runtime_GetSubstitution) {
22 HandleScope scope(isolate);
23 DCHECK_EQ(5, args.length());
24 CONVERT_ARG_HANDLE_CHECKED(String, matched, 0);
25 CONVERT_ARG_HANDLE_CHECKED(String, subject, 1);
26 CONVERT_SMI_ARG_CHECKED(position, 2);
27 CONVERT_ARG_HANDLE_CHECKED(String, replacement, 3);
28 CONVERT_SMI_ARG_CHECKED(start_index, 4);
29
30 // A simple match without captures.
31 class SimpleMatch : public String::Match {
32 public:
33 SimpleMatch(Handle<String> match, Handle<String> prefix,
34 Handle<String> suffix)
35 : match_(match), prefix_(prefix), suffix_(suffix) {}
36
37 Handle<String> GetMatch() override { return match_; }
38 Handle<String> GetPrefix() override { return prefix_; }
39 Handle<String> GetSuffix() override { return suffix_; }
40
41 int CaptureCount() override { return 0; }
42 bool HasNamedCaptures() override { return false; }
43 MaybeHandle<String> GetCapture(int i, bool* capture_exists) override {
44 *capture_exists = false;
45 return match_; // Return arbitrary string handle.
46 }
47 MaybeHandle<String> GetNamedCapture(Handle<String> name,
48 CaptureState* state) override {
49 UNREACHABLE();
50 }
51
52 private:
53 Handle<String> match_, prefix_, suffix_;
54 };
55
56 Handle<String> prefix =
57 isolate->factory()->NewSubString(subject, 0, position);
58 Handle<String> suffix = isolate->factory()->NewSubString(
59 subject, position + matched->length(), subject->length());
60 SimpleMatch match(matched, prefix, suffix);
61
62 RETURN_RESULT_OR_FAILURE(
63 isolate,
64 String::GetSubstitution(isolate, &match, replacement, start_index));
65 }
66
67 // This may return an empty MaybeHandle if an exception is thrown or
68 // we abort due to reaching the recursion limit.
StringReplaceOneCharWithString(Isolate * isolate,Handle<String> subject,Handle<String> search,Handle<String> replace,bool * found,int recursion_limit)69 MaybeHandle<String> StringReplaceOneCharWithString(
70 Isolate* isolate, Handle<String> subject, Handle<String> search,
71 Handle<String> replace, bool* found, int recursion_limit) {
72 StackLimitCheck stackLimitCheck(isolate);
73 if (stackLimitCheck.HasOverflowed() || (recursion_limit == 0)) {
74 return MaybeHandle<String>();
75 }
76 recursion_limit--;
77 if (subject->IsConsString()) {
78 ConsString cons = ConsString::cast(*subject);
79 Handle<String> first = handle(cons.first(), isolate);
80 Handle<String> second = handle(cons.second(), isolate);
81 Handle<String> new_first;
82 if (!StringReplaceOneCharWithString(isolate, first, search, replace, found,
83 recursion_limit).ToHandle(&new_first)) {
84 return MaybeHandle<String>();
85 }
86 if (*found) return isolate->factory()->NewConsString(new_first, second);
87
88 Handle<String> new_second;
89 if (!StringReplaceOneCharWithString(isolate, second, search, replace, found,
90 recursion_limit)
91 .ToHandle(&new_second)) {
92 return MaybeHandle<String>();
93 }
94 if (*found) return isolate->factory()->NewConsString(first, new_second);
95
96 return subject;
97 } else {
98 int index = String::IndexOf(isolate, subject, search, 0);
99 if (index == -1) return subject;
100 *found = true;
101 Handle<String> first = isolate->factory()->NewSubString(subject, 0, index);
102 Handle<String> cons1;
103 ASSIGN_RETURN_ON_EXCEPTION(
104 isolate, cons1, isolate->factory()->NewConsString(first, replace),
105 String);
106 Handle<String> second =
107 isolate->factory()->NewSubString(subject, index + 1, subject->length());
108 return isolate->factory()->NewConsString(cons1, second);
109 }
110 }
111
RUNTIME_FUNCTION(Runtime_StringReplaceOneCharWithString)112 RUNTIME_FUNCTION(Runtime_StringReplaceOneCharWithString) {
113 HandleScope scope(isolate);
114 DCHECK_EQ(3, args.length());
115 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
116 CONVERT_ARG_HANDLE_CHECKED(String, search, 1);
117 CONVERT_ARG_HANDLE_CHECKED(String, replace, 2);
118
119 // If the cons string tree is too deep, we simply abort the recursion and
120 // retry with a flattened subject string.
121 const int kRecursionLimit = 0x1000;
122 bool found = false;
123 Handle<String> result;
124 if (StringReplaceOneCharWithString(isolate, subject, search, replace, &found,
125 kRecursionLimit).ToHandle(&result)) {
126 return *result;
127 }
128 if (isolate->has_pending_exception())
129 return ReadOnlyRoots(isolate).exception();
130
131 subject = String::Flatten(isolate, subject);
132 if (StringReplaceOneCharWithString(isolate, subject, search, replace, &found,
133 kRecursionLimit).ToHandle(&result)) {
134 return *result;
135 }
136 if (isolate->has_pending_exception())
137 return ReadOnlyRoots(isolate).exception();
138 // In case of empty handle and no pending exception we have stack overflow.
139 return isolate->StackOverflow();
140 }
141
RUNTIME_FUNCTION(Runtime_StringTrim)142 RUNTIME_FUNCTION(Runtime_StringTrim) {
143 HandleScope scope(isolate);
144 DCHECK_EQ(2, args.length());
145 Handle<String> string = args.at<String>(0);
146 CONVERT_SMI_ARG_CHECKED(mode, 1);
147 String::TrimMode trim_mode = static_cast<String::TrimMode>(mode);
148 return *String::Trim(isolate, string, trim_mode);
149 }
150
151 // ES6 #sec-string.prototype.includes
152 // String.prototype.includes(searchString [, position])
RUNTIME_FUNCTION(Runtime_StringIncludes)153 RUNTIME_FUNCTION(Runtime_StringIncludes) {
154 HandleScope scope(isolate);
155 DCHECK_EQ(3, args.length());
156
157 Handle<Object> receiver = args.at(0);
158 if (receiver->IsNullOrUndefined(isolate)) {
159 THROW_NEW_ERROR_RETURN_FAILURE(
160 isolate, NewTypeError(MessageTemplate::kCalledOnNullOrUndefined,
161 isolate->factory()->NewStringFromAsciiChecked(
162 "String.prototype.includes")));
163 }
164 Handle<String> receiver_string;
165 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, receiver_string,
166 Object::ToString(isolate, receiver));
167
168 // Check if the search string is a regExp and fail if it is.
169 Handle<Object> search = args.at(1);
170 Maybe<bool> is_reg_exp = RegExpUtils::IsRegExp(isolate, search);
171 if (is_reg_exp.IsNothing()) {
172 DCHECK(isolate->has_pending_exception());
173 return ReadOnlyRoots(isolate).exception();
174 }
175 if (is_reg_exp.FromJust()) {
176 THROW_NEW_ERROR_RETURN_FAILURE(
177 isolate, NewTypeError(MessageTemplate::kFirstArgumentNotRegExp,
178 isolate->factory()->NewStringFromStaticChars(
179 "String.prototype.includes")));
180 }
181 Handle<String> search_string;
182 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, search_string,
183 Object::ToString(isolate, args.at(1)));
184 Handle<Object> position;
185 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, position,
186 Object::ToInteger(isolate, args.at(2)));
187
188 uint32_t index = receiver_string->ToValidIndex(*position);
189 int index_in_str =
190 String::IndexOf(isolate, receiver_string, search_string, index);
191 return *isolate->factory()->ToBoolean(index_in_str != -1);
192 }
193
194 // ES6 #sec-string.prototype.indexof
195 // String.prototype.indexOf(searchString [, position])
RUNTIME_FUNCTION(Runtime_StringIndexOf)196 RUNTIME_FUNCTION(Runtime_StringIndexOf) {
197 HandleScope scope(isolate);
198 DCHECK_EQ(3, args.length());
199 return String::IndexOf(isolate, args.at(0), args.at(1), args.at(2));
200 }
201
202 // ES6 #sec-string.prototype.indexof
203 // String.prototype.indexOf(searchString, position)
204 // Fast version that assumes that does not perform conversions of the incoming
205 // arguments.
RUNTIME_FUNCTION(Runtime_StringIndexOfUnchecked)206 RUNTIME_FUNCTION(Runtime_StringIndexOfUnchecked) {
207 HandleScope scope(isolate);
208 DCHECK_EQ(3, args.length());
209 Handle<String> receiver_string = args.at<String>(0);
210 Handle<String> search_string = args.at<String>(1);
211 int index = std::min(std::max(args.smi_at(2), 0), receiver_string->length());
212
213 return Smi::FromInt(String::IndexOf(isolate, receiver_string, search_string,
214 static_cast<uint32_t>(index)));
215 }
216
RUNTIME_FUNCTION(Runtime_StringLastIndexOf)217 RUNTIME_FUNCTION(Runtime_StringLastIndexOf) {
218 HandleScope handle_scope(isolate);
219 return String::LastIndexOf(isolate, args.at(0), args.at(1),
220 isolate->factory()->undefined_value());
221 }
222
RUNTIME_FUNCTION(Runtime_StringSubstring)223 RUNTIME_FUNCTION(Runtime_StringSubstring) {
224 HandleScope scope(isolate);
225 DCHECK_EQ(3, args.length());
226 CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
227 CONVERT_INT32_ARG_CHECKED(start, 1);
228 CONVERT_INT32_ARG_CHECKED(end, 2);
229 DCHECK_LE(0, start);
230 DCHECK_LE(start, end);
231 DCHECK_LE(end, string->length());
232 isolate->counters()->sub_string_runtime()->Increment();
233 return *isolate->factory()->NewSubString(string, start, end);
234 }
235
RUNTIME_FUNCTION(Runtime_StringAdd)236 RUNTIME_FUNCTION(Runtime_StringAdd) {
237 HandleScope scope(isolate);
238 DCHECK_EQ(2, args.length());
239 CONVERT_ARG_HANDLE_CHECKED(String, str1, 0);
240 CONVERT_ARG_HANDLE_CHECKED(String, str2, 1);
241 isolate->counters()->string_add_runtime()->Increment();
242 RETURN_RESULT_OR_FAILURE(isolate,
243 isolate->factory()->NewConsString(str1, str2));
244 }
245
246
RUNTIME_FUNCTION(Runtime_InternalizeString)247 RUNTIME_FUNCTION(Runtime_InternalizeString) {
248 HandleScope handles(isolate);
249 DCHECK_EQ(1, args.length());
250 CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
251 return *isolate->factory()->InternalizeString(string);
252 }
253
RUNTIME_FUNCTION(Runtime_StringCharCodeAt)254 RUNTIME_FUNCTION(Runtime_StringCharCodeAt) {
255 HandleScope handle_scope(isolate);
256 DCHECK_EQ(2, args.length());
257
258 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
259 CONVERT_NUMBER_CHECKED(uint32_t, i, Uint32, args[1]);
260
261 // Flatten the string. If someone wants to get a char at an index
262 // in a cons string, it is likely that more indices will be
263 // accessed.
264 subject = String::Flatten(isolate, subject);
265
266 if (i >= static_cast<uint32_t>(subject->length())) {
267 return ReadOnlyRoots(isolate).nan_value();
268 }
269
270 return Smi::FromInt(subject->Get(i));
271 }
272
RUNTIME_FUNCTION(Runtime_StringBuilderConcat)273 RUNTIME_FUNCTION(Runtime_StringBuilderConcat) {
274 HandleScope scope(isolate);
275 DCHECK_EQ(3, args.length());
276 CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
277 int32_t array_length;
278 if (!args[1].ToInt32(&array_length)) {
279 THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
280 }
281 CONVERT_ARG_HANDLE_CHECKED(String, special, 2);
282
283 size_t actual_array_length = 0;
284 CHECK(TryNumberToSize(array->length(), &actual_array_length));
285 CHECK_GE(array_length, 0);
286 CHECK(static_cast<size_t>(array_length) <= actual_array_length);
287
288 // This assumption is used by the slice encoding in one or two smis.
289 DCHECK_GE(Smi::kMaxValue, String::kMaxLength);
290
291 CHECK(array->HasFastElements());
292 JSObject::EnsureCanContainHeapObjectElements(array);
293
294 int special_length = special->length();
295 if (!array->HasObjectElements()) {
296 return isolate->Throw(ReadOnlyRoots(isolate).illegal_argument_string());
297 }
298
299 int length;
300 bool one_byte = special->IsOneByteRepresentation();
301
302 {
303 DisallowHeapAllocation no_gc;
304 FixedArray fixed_array = FixedArray::cast(array->elements());
305 if (fixed_array.length() < array_length) {
306 array_length = fixed_array.length();
307 }
308
309 if (array_length == 0) {
310 return ReadOnlyRoots(isolate).empty_string();
311 } else if (array_length == 1) {
312 Object first = fixed_array.get(0);
313 if (first.IsString()) return first;
314 }
315 length = StringBuilderConcatLength(special_length, fixed_array,
316 array_length, &one_byte);
317 }
318
319 if (length == -1) {
320 return isolate->Throw(ReadOnlyRoots(isolate).illegal_argument_string());
321 }
322 if (length == 0) {
323 return ReadOnlyRoots(isolate).empty_string();
324 }
325
326 if (one_byte) {
327 Handle<SeqOneByteString> answer;
328 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
329 isolate, answer, isolate->factory()->NewRawOneByteString(length));
330 DisallowHeapAllocation no_gc;
331 StringBuilderConcatHelper(*special, answer->GetChars(no_gc),
332 FixedArray::cast(array->elements()),
333 array_length);
334 return *answer;
335 } else {
336 Handle<SeqTwoByteString> answer;
337 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
338 isolate, answer, isolate->factory()->NewRawTwoByteString(length));
339 DisallowHeapAllocation no_gc;
340 StringBuilderConcatHelper(*special, answer->GetChars(no_gc),
341 FixedArray::cast(array->elements()),
342 array_length);
343 return *answer;
344 }
345 }
346
347
348 // Copies Latin1 characters to the given fixed array looking up
349 // one-char strings in the cache. Gives up on the first char that is
350 // not in the cache and fills the remainder with smi zeros. Returns
351 // the length of the successfully copied prefix.
CopyCachedOneByteCharsToArray(Heap * heap,const uint8_t * chars,FixedArray elements,int length)352 static int CopyCachedOneByteCharsToArray(Heap* heap, const uint8_t* chars,
353 FixedArray elements, int length) {
354 DisallowHeapAllocation no_gc;
355 FixedArray one_byte_cache = heap->single_character_string_cache();
356 Object undefined = ReadOnlyRoots(heap).undefined_value();
357 int i;
358 WriteBarrierMode mode = elements.GetWriteBarrierMode(no_gc);
359 for (i = 0; i < length; ++i) {
360 Object value = one_byte_cache.get(chars[i]);
361 if (value == undefined) break;
362 elements.set(i, value, mode);
363 }
364 if (i < length) {
365 MemsetTagged(elements.RawFieldOfElementAt(i), Smi::zero(), length - i);
366 }
367 #ifdef DEBUG
368 for (int j = 0; j < length; ++j) {
369 Object element = elements.get(j);
370 DCHECK(element == Smi::zero() ||
371 (element.IsString() && String::cast(element).LooksValid()));
372 }
373 #endif
374 return i;
375 }
376
377 // Converts a String to JSArray.
378 // For example, "foo" => ["f", "o", "o"].
RUNTIME_FUNCTION(Runtime_StringToArray)379 RUNTIME_FUNCTION(Runtime_StringToArray) {
380 HandleScope scope(isolate);
381 DCHECK_EQ(2, args.length());
382 CONVERT_ARG_HANDLE_CHECKED(String, s, 0);
383 CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[1]);
384
385 s = String::Flatten(isolate, s);
386 const int length = static_cast<int>(Min<uint32_t>(s->length(), limit));
387
388 Handle<FixedArray> elements;
389 int position = 0;
390 if (s->IsFlat() && s->IsOneByteRepresentation()) {
391 // Try using cached chars where possible.
392 elements = isolate->factory()->NewUninitializedFixedArray(length);
393
394 DisallowHeapAllocation no_gc;
395 String::FlatContent content = s->GetFlatContent(no_gc);
396 if (content.IsOneByte()) {
397 Vector<const uint8_t> chars = content.ToOneByteVector();
398 // Note, this will initialize all elements (not only the prefix)
399 // to prevent GC from seeing partially initialized array.
400 position = CopyCachedOneByteCharsToArray(isolate->heap(), chars.begin(),
401 *elements, length);
402 } else {
403 MemsetTagged(elements->data_start(),
404 ReadOnlyRoots(isolate).undefined_value(), length);
405 }
406 } else {
407 elements = isolate->factory()->NewFixedArray(length);
408 }
409 for (int i = position; i < length; ++i) {
410 Handle<Object> str =
411 isolate->factory()->LookupSingleCharacterStringFromCode(s->Get(i));
412 elements->set(i, *str);
413 }
414
415 #ifdef DEBUG
416 for (int i = 0; i < length; ++i) {
417 DCHECK_EQ(String::cast(elements->get(i)).length(), 1);
418 }
419 #endif
420
421 return *isolate->factory()->NewJSArrayWithElements(elements);
422 }
423
RUNTIME_FUNCTION(Runtime_StringLessThan)424 RUNTIME_FUNCTION(Runtime_StringLessThan) {
425 HandleScope handle_scope(isolate);
426 DCHECK_EQ(2, args.length());
427 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
428 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
429 ComparisonResult result = String::Compare(isolate, x, y);
430 DCHECK_NE(result, ComparisonResult::kUndefined);
431 return isolate->heap()->ToBoolean(
432 ComparisonResultToBool(Operation::kLessThan, result));
433 }
434
RUNTIME_FUNCTION(Runtime_StringLessThanOrEqual)435 RUNTIME_FUNCTION(Runtime_StringLessThanOrEqual) {
436 HandleScope handle_scope(isolate);
437 DCHECK_EQ(2, args.length());
438 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
439 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
440 ComparisonResult result = String::Compare(isolate, x, y);
441 DCHECK_NE(result, ComparisonResult::kUndefined);
442 return isolate->heap()->ToBoolean(
443 ComparisonResultToBool(Operation::kLessThanOrEqual, result));
444 }
445
RUNTIME_FUNCTION(Runtime_StringGreaterThan)446 RUNTIME_FUNCTION(Runtime_StringGreaterThan) {
447 HandleScope handle_scope(isolate);
448 DCHECK_EQ(2, args.length());
449 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
450 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
451 ComparisonResult result = String::Compare(isolate, x, y);
452 DCHECK_NE(result, ComparisonResult::kUndefined);
453 return isolate->heap()->ToBoolean(
454 ComparisonResultToBool(Operation::kGreaterThan, result));
455 }
456
RUNTIME_FUNCTION(Runtime_StringGreaterThanOrEqual)457 RUNTIME_FUNCTION(Runtime_StringGreaterThanOrEqual) {
458 HandleScope handle_scope(isolate);
459 DCHECK_EQ(2, args.length());
460 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
461 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
462 ComparisonResult result = String::Compare(isolate, x, y);
463 DCHECK_NE(result, ComparisonResult::kUndefined);
464 return isolate->heap()->ToBoolean(
465 ComparisonResultToBool(Operation::kGreaterThanOrEqual, result));
466 }
467
RUNTIME_FUNCTION(Runtime_StringEqual)468 RUNTIME_FUNCTION(Runtime_StringEqual) {
469 HandleScope handle_scope(isolate);
470 DCHECK_EQ(2, args.length());
471 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
472 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
473 return isolate->heap()->ToBoolean(String::Equals(isolate, x, y));
474 }
475
RUNTIME_FUNCTION(Runtime_FlattenString)476 RUNTIME_FUNCTION(Runtime_FlattenString) {
477 HandleScope scope(isolate);
478 DCHECK_EQ(1, args.length());
479 CONVERT_ARG_HANDLE_CHECKED(String, str, 0);
480 return *String::Flatten(isolate, str);
481 }
482
RUNTIME_FUNCTION(Runtime_StringMaxLength)483 RUNTIME_FUNCTION(Runtime_StringMaxLength) {
484 SealHandleScope shs(isolate);
485 return Smi::FromInt(String::kMaxLength);
486 }
487
RUNTIME_FUNCTION(Runtime_StringCompareSequence)488 RUNTIME_FUNCTION(Runtime_StringCompareSequence) {
489 HandleScope handle_scope(isolate);
490 DCHECK_EQ(3, args.length());
491 CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
492 CONVERT_ARG_HANDLE_CHECKED(String, search_string, 1);
493 CONVERT_NUMBER_CHECKED(int, start, Int32, args[2]);
494
495 // Check if start + searchLength is in bounds.
496 DCHECK_LE(start + search_string->length(), string->length());
497
498 FlatStringReader string_reader(isolate, String::Flatten(isolate, string));
499 FlatStringReader search_reader(isolate,
500 String::Flatten(isolate, search_string));
501
502 for (int i = 0; i < search_string->length(); i++) {
503 if (string_reader.Get(start + i) != search_reader.Get(i)) {
504 return ReadOnlyRoots(isolate).false_value();
505 }
506 }
507
508 return ReadOnlyRoots(isolate).true_value();
509 }
510
RUNTIME_FUNCTION(Runtime_StringEscapeQuotes)511 RUNTIME_FUNCTION(Runtime_StringEscapeQuotes) {
512 HandleScope handle_scope(isolate);
513 DCHECK_EQ(1, args.length());
514 CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
515
516 // Equivalent to global replacement `string.replace(/"/g, """)`, but this
517 // does not modify any global state (e.g. the regexp match info).
518
519 const int string_length = string->length();
520 Handle<String> quotes =
521 isolate->factory()->LookupSingleCharacterStringFromCode('"');
522
523 int index = String::IndexOf(isolate, string, quotes, 0);
524
525 // No quotes, nothing to do.
526 if (index == -1) return *string;
527
528 // Find all quotes.
529 std::vector<int> indices = {index};
530 while (index + 1 < string_length) {
531 index = String::IndexOf(isolate, string, quotes, index + 1);
532 if (index == -1) break;
533 indices.emplace_back(index);
534 }
535
536 // Build the replacement string.
537 Handle<String> replacement =
538 isolate->factory()->NewStringFromAsciiChecked(""");
539 const int estimated_part_count = static_cast<int>(indices.size()) * 2 + 1;
540 ReplacementStringBuilder builder(isolate->heap(), string,
541 estimated_part_count);
542
543 int prev_index = -1; // Start at -1 to avoid special-casing the first match.
544 for (int index : indices) {
545 const int slice_start = prev_index + 1;
546 const int slice_end = index;
547 if (slice_end > slice_start) {
548 builder.AddSubjectSlice(slice_start, slice_end);
549 }
550 builder.AddString(replacement);
551 prev_index = index;
552 }
553
554 if (prev_index < string_length - 1) {
555 builder.AddSubjectSlice(prev_index + 1, string_length);
556 }
557
558 return *builder.ToString().ToHandleChecked();
559 }
560
561 } // namespace internal
562 } // namespace v8
563