Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/string_bytes.cc
Original file line number Diff line number Diff line change
Expand Up @@ -506,8 +506,10 @@ Maybe<size_t> StringBytes::Size(Isolate* isolate,
return Just<size_t>(simdutf::utf8_length_from_latin1(
reinterpret_cast<const char*>(view.data8()), view.length()));
}
return Just<size_t>(simdutf::utf8_length_from_utf16(
reinterpret_cast<const char16_t*>(view.data16()), view.length()));
return Just<size_t>(
simdutf::utf8_length_from_utf16_with_replacement(
reinterpret_cast<const char16_t*>(view.data16()), view.length())
.count);

case UCS2:
return Just(view.length() * sizeof(uint16_t));
Expand Down
26 changes: 26 additions & 0 deletions test/parallel/test-buffer-indexof.js
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,32 @@ assert.strictEqual(reallyLong.lastIndexOf(pattern), 0);
assert.strictEqual(haystack.lastIndexOf(needle), haystack.length - 3);
}

// UTF-8 string search should use the same replacement-character semantics
// as Buffer.from() for unpaired UTF-16 surrogates.
{
const prefix = 'a'.repeat(16);
const suffix = 'b'.repeat(16);
const needles = [
`${prefix}${String.fromCharCode(0xd800)}${suffix}`,
`${prefix}${String.fromCharCode(0xdc00)}${suffix}`,
JSON.parse(`{"needle":"${prefix}\\ud800${suffix}"}`).needle,
];

for (const needle of needles) {
const needleBuffer = Buffer.from(needle, 'utf8');
const haystack = Buffer.concat([
Buffer.from('xx'),
needleBuffer,
Buffer.from('yy'),
]);

assert.strictEqual(Buffer.byteLength(needle, 'utf8'), needleBuffer.length);
assert.strictEqual(haystack.indexOf(needle, 0, 'utf8'), 2);
assert.strictEqual(haystack.lastIndexOf(needle, haystack.length - 1, 'utf8'), 2);
assert.strictEqual(haystack.includes(needle, 0, 'utf8'), true);
}
}

// Avoid abort because of invalid usage
// see https://github.com/nodejs/node/issues/32753
{
Expand Down
Loading