diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 99fb37ef186b..5c5bbe86e504 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -1086,6 +1086,10 @@ void IndexOfString(const FunctionCallbackInfo& 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) { diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 4bed7f935b87..f23c84bdf2ea 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -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.