Skip to content

Commit f205177

Browse files
authored
buffer: fix odd UTF-16LE indexOf start
UTF-16LE string searches rounded odd forward start offsets down, allowing a match before the requested range. Round the start up to the next code-unit boundary while leaving reverse search and the existing 16-bit implementation unchanged. Assisted-by: Codex Signed-off-by: inoway46 <inoueyuya416@gmail.com> PR-URL: #65960 Fixes: #26448 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent a3bb551 commit f205177

2 files changed

Lines changed: 10 additions & 0 deletions

File tree

‎src/node_buffer.cc‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1086,6 +1086,10 @@ void IndexOfString(const FunctionCallbackInfo<Value>& args) {
10861086
} else if (is_forward && offset >= search_end) {
10871087
return args.GetReturnValue().Set(-1);
10881088
}
1089+
if (enc == UCS2 && is_forward) {
1090+
offset += offset % sizeof(uint16_t);
1091+
if (offset >= search_end) return args.GetReturnValue().Set(-1);
1092+
}
10891093
CHECK_LT(offset, haystack_length);
10901094
if ((is_forward && needle_length + offset > search_end) ||
10911095
needle_length > search_end) {

‎test/parallel/test-buffer-indexof.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,12 @@ assert.strictEqual(Buffer.from('aaaa').indexOf('你好', 'ucs2'), -1);
308308
// Haystack has odd length, but the needle is UCS2.
309309
assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1);
310310

311+
{
312+
const buf = Buffer.from('\u6881\u6882\u6881', 'utf16le');
313+
assert.strictEqual(buf.indexOf('\u6881', 1, 'utf16le'), 4);
314+
assert.strictEqual(buf.indexOf('\u6881', -1, 'utf16le'), -1);
315+
}
316+
311317
{
312318
// Find substrings in Utf8.
313319
const lengths = [1, 3, 15]; // Single char, simple and complex.

0 commit comments

Comments
 (0)