Skip to content

Commit 8b077fa

Browse files
addaleaxMyles Borins
authored and
Myles Borins
committed
buffer: fix UCS2 indexOf for odd buffer length
Fix `buffer.indexOf` for the case that the haystack has odd length and the needle is not found in it. `StringSearch()` would return the length of the buffer in multiples of `sizeof(uint16_t)`, but checking that against `haystack_length` would not work if the latter one was odd. PR-URL: #6511 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trevor Norris <trev.norris@gmail.com>
1 parent 12a9699 commit 8b077fa

File tree

2 files changed

+6
-1
lines changed

2 files changed

+6
-1
lines changed

src/node_buffer.cc

+3-1
Original file line numberDiff line numberDiff line change
@@ -826,7 +826,9 @@ void IndexOfString(const FunctionCallbackInfo<Value>& args) {
826826

827827
Local<String> needle = args[1].As<String>();
828828
const char* haystack = ts_obj_data;
829-
const size_t haystack_length = ts_obj_length;
829+
// Round down to the nearest multiple of 2 in case of UCS2.
830+
const size_t haystack_length = (enc == UCS2) ?
831+
ts_obj_length &~ 1 : ts_obj_length; // NOLINT(whitespace/operators)
830832

831833
const size_t needle_length =
832834
StringBytes::Size(args.GetIsolate(), needle, enc);

test/parallel/test-buffer-indexof.js

+3
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,9 @@ assert.strictEqual(new Buffer('aaaa').indexOf('a'.repeat(4), 'ucs2'), -1);
239239
assert.strictEqual(new Buffer('aaaa').indexOf('a'.repeat(4), 'utf8'), 0);
240240
assert.strictEqual(new Buffer('aaaa').indexOf('你好', 'ucs2'), -1);
241241

242+
// Haystack has odd length, but the needle is UCS2.
243+
assert.strictEqual(new Buffer('aaaaa').indexOf('b', 'ucs2'), -1);
244+
242245
{
243246
// Find substrings in Utf8.
244247
const lengths = [1, 3, 15]; // Single char, simple and complex.

0 commit comments

Comments
 (0)