Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 12a9699

Browse filesBrowse 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 <jasnell@gmail.com> Reviewed-By: Trevor Norris <trev.norris@gmail.com>
1 parent 7b60b8f commit 12a9699
Copy full SHA for 12a9699

File tree

Expand file treeCollapse file tree

2 files changed

+8
-2
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

2 files changed

+8
-2
lines changed
Open diff view settings
Collapse file

‎src/node_buffer.cc‎

Copy file name to clipboardExpand all lines: src/node_buffer.cc
+2-2Lines 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) {
Collapse file

‎test/parallel/test-buffer-indexof.js‎

Copy file name to clipboardExpand all lines: test/parallel/test-buffer-indexof.js
+6Lines 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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.