Skip to content

Commit 54cd2e1

Browse files
committed
buffer: properly retrieve binary length of needle
If the needle contains an extended latin-1 character then using String::Utf8Length() will be too large and the search will return early. Instead use String::Length() when encoding is BINARY. PR-URL: #4803 Reviewed-By: James M Snell <[email protected]>
1 parent 7240ad4 commit 54cd2e1

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

src/node_buffer.cc

+3-1
Original file line numberDiff line numberDiff line change
@@ -849,7 +849,9 @@ void IndexOfString(const FunctionCallbackInfo<Value>& args) {
849849
Local<String> needle = args[1].As<String>();
850850
const char* haystack = ts_obj_data;
851851
const size_t haystack_length = ts_obj_length;
852-
const size_t needle_length = needle->Utf8Length();
852+
// Extended latin-1 characters are 2 bytes in Utf8.
853+
const size_t needle_length =
854+
enc == BINARY ? needle->Length() : needle->Utf8Length();
853855

854856

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

test/parallel/test-buffer-indexof.js

+9
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,15 @@ assert.equal(
109109
assert.equal(
110110
Buffer(b.toString('binary'), 'binary')
111111
.indexOf(Buffer('d', 'binary'), 0, 'binary'), 3);
112+
assert.equal(
113+
Buffer('aa\u00e8aa', 'binary')
114+
.indexOf('\u00e8', 'binary'), 2);
115+
assert.equal(
116+
Buffer('\u00e8', 'binary')
117+
.indexOf('\u00e8', 'binary'), 0);
118+
assert.equal(
119+
Buffer('\u00e8', 'binary')
120+
.indexOf(Buffer('\u00e8', 'binary'), 'binary'), 0);
112121

113122

114123
// test optional offset with passed encoding

0 commit comments

Comments
 (0)