Skip to content

Commit 12a9699

Browse files
addaleaxMyles Borins
authored andcommitted
buffer: fix needle length misestimation for UCS2
Use `StringBytes::Size` to determine the needle string length instead of assuming latin-1 or UTF-8. Previously, `Buffer.indexOf` could fail with an assertion failure when the needle's byte length, but not its character count, exceeded the haystack's byte length. PR-URL: #6511 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Trevor Norris <[email protected]>
1 parent 7b60b8f commit 12a9699

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

src/node_buffer.cc

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -827,9 +827,9 @@ void IndexOfString(const FunctionCallbackInfo<Value>& args) {
827827
Local<String> needle = args[1].As<String>();
828828
const char* haystack = ts_obj_data;
829829
const size_t haystack_length = ts_obj_length;
830-
// Extended latin-1 characters are 2 bytes in Utf8.
830+
831831
const size_t needle_length =
832-
enc == BINARY ? needle->Length() : needle->Utf8Length();
832+
StringBytes::Size(args.GetIsolate(), needle, enc);
833833

834834

835835
if (needle_length == 0 || haystack_length == 0) {

test/parallel/test-buffer-indexof.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,12 @@ var allCharsBufferUcs2 = new Buffer(allCharsString, 'ucs2');
233233
assert.equal(-1, allCharsBufferUtf8.indexOf('notfound'));
234234
assert.equal(-1, allCharsBufferUcs2.indexOf('notfound'));
235235

236+
// Needle is longer than haystack, but only because it's encoded as UTF-16
237+
assert.strictEqual(new Buffer('aaaa').indexOf('a'.repeat(4), 'ucs2'), -1);
238+
239+
assert.strictEqual(new Buffer('aaaa').indexOf('a'.repeat(4), 'utf8'), 0);
240+
assert.strictEqual(new Buffer('aaaa').indexOf('你好', 'ucs2'), -1);
241+
236242
{
237243
// Find substrings in Utf8.
238244
const lengths = [1, 3, 15]; // Single char, simple and complex.

0 commit comments

Comments
 (0)