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: https://github.com/nodejs/node/pull/65960
Fixes: https://github.com/nodejs/node/issues/26448
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Yuya Inoue authored and GitHub committed 2026-09-25 08:44:58 +00:00
1 parent a3bb551ea7
commit f205177842
2 files changed
+10

No files matched your search

+4
View File
@@ -1086,6 +1086,10 @@ void IndexOfString(const FunctionCallbackInfo<Value>& args) {
} else if (is_forward && offset >= search_end) {
return args.GetReturnValue().Set(-1);
}
if (enc == UCS2 && is_forward) {
offset += offset % sizeof(uint16_t);
if (offset >= search_end) return args.GetReturnValue().Set(-1);
}
CHECK_LT(offset, haystack_length);
if ((is_forward && needle_length + offset > search_end) ||
needle_length > search_end) {
+6
View File
@@ -308,6 +308,12 @@ assert.strictEqual(Buffer.from('aaaa').indexOf('你好', 'ucs2'), -1);
// Haystack has odd length, but the needle is UCS2.
assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1);
{
const buf = Buffer.from('\u6881\u6882\u6881', 'utf16le');
assert.strictEqual(buf.indexOf('\u6881', 1, 'utf16le'), 4);
assert.strictEqual(buf.indexOf('\u6881', -1, 'utf16le'), -1);
}
{
// Find substrings in Utf8.
const lengths = [1, 3, 15]; // Single char, simple and complex.