diff --git a/src/node_buffer.cc b/src/node_buffer.cc index dccd6faeef5330..83efaab210ea6f 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -826,7 +826,9 @@ void IndexOfString(const FunctionCallbackInfo& args) { Local needle = args[1].As(); const char* haystack = ts_obj_data; - const size_t haystack_length = ts_obj_length; + // Round down to the nearest multiple of 2 in case of UCS2. + const size_t haystack_length = (enc == UCS2) ? + ts_obj_length &~ 1 : ts_obj_length; // NOLINT(whitespace/operators) const size_t needle_length = StringBytes::Size(args.GetIsolate(), needle, enc); diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index b085b4b1ea66ff..06dfc3af0896c5 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -239,6 +239,9 @@ assert.strictEqual(new Buffer('aaaa').indexOf('a'.repeat(4), 'ucs2'), -1); assert.strictEqual(new Buffer('aaaa').indexOf('a'.repeat(4), 'utf8'), 0); assert.strictEqual(new Buffer('aaaa').indexOf('你好', 'ucs2'), -1); +// Haystack has odd length, but the needle is UCS2. +assert.strictEqual(new Buffer('aaaaa').indexOf('b', 'ucs2'), -1); + { // Find substrings in Utf8. const lengths = [1, 3, 15]; // Single char, simple and complex.