Skip to content

Commit 9cd14ce

Browse files
addaleaxevanlucas
authored andcommitted
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 <[email protected]> Reviewed-By: Trevor Norris <[email protected]>
1 parent a550ddb commit 9cd14ce

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
@@ -994,7 +994,9 @@ void IndexOfString(const FunctionCallbackInfo<Value>& args) {
994994
bool is_forward = args[4]->IsTrue();
995995

996996
const char* haystack = ts_obj_data;
997-
const size_t haystack_length = ts_obj_length;
997+
// Round down to the nearest multiple of 2 in case of UCS2.
998+
const size_t haystack_length = (enc == UCS2) ?
999+
ts_obj_length &~ 1 : ts_obj_length; // NOLINT(whitespace/operators)
9981000

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

test/parallel/test-buffer-indexof.js

+3
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,9 @@ assert.strictEqual(Buffer.from('aaaa').indexOf('a'.repeat(4), 'ucs2'), -1);
228228
assert.strictEqual(Buffer.from('aaaa').indexOf('a'.repeat(4), 'utf8'), 0);
229229
assert.strictEqual(Buffer.from('aaaa').indexOf('你好', 'ucs2'), -1);
230230

231+
// Haystack has odd length, but the needle is UCS2.
232+
assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1);
233+
231234
{
232235
// Find substrings in Utf8.
233236
const lengths = [1, 3, 15]; // Single char, simple and complex.

0 commit comments

Comments
 (0)