From 288f4c22067aa37b92625159cc58a2383172e20c Mon Sep 17 00:00:00 2001 From: Trevor Norris Date: Thu, 21 Jan 2016 14:00:59 -0700 Subject: [PATCH] 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: https://github.com/nodejs/node/pull/4803 Reviewed-By: James M Snell --- src/node_buffer.cc | 4 +++- test/parallel/test-buffer-indexof.js | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 35dfcca15c2ed3..90c5ee9d7797ca 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -827,7 +827,9 @@ void IndexOfString(const FunctionCallbackInfo& args) { Local needle = args[1].As(); const char* haystack = ts_obj_data; const size_t haystack_length = ts_obj_length; - const size_t needle_length = needle->Utf8Length(); + // Extended latin-1 characters are 2 bytes in Utf8. + const size_t needle_length = + enc == BINARY ? needle->Length() : needle->Utf8Length(); if (needle_length == 0 || haystack_length == 0) { diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 221176c40f2777..8ed384aea58878 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -109,6 +109,15 @@ assert.equal( assert.equal( Buffer(b.toString('binary'), 'binary') .indexOf(Buffer('d', 'binary'), 0, 'binary'), 3); +assert.equal( + Buffer('aa\u00e8aa', 'binary') + .indexOf('\u00e8', 'binary'), 2); +assert.equal( + Buffer('\u00e8', 'binary') + .indexOf('\u00e8', 'binary'), 0); +assert.equal( + Buffer('\u00e8', 'binary') + .indexOf(Buffer('\u00e8', 'binary'), 'binary'), 0); { // test usc2 encoding