From 85e06a2e34ad8719c29381e5acb6fc9cdc269815 Mon Sep 17 00:00:00 2001 From: Trevor Norris Date: Thu, 21 Jan 2016 13:51:09 -0700 Subject: [PATCH] buffer: allow encoding param to collapse Currently the signature is indexOf(val[, byteOffset[, encoding]]) Instead allow indexOf(val[, byteOffset][, encoding]) so that byteOffset does not need to be passed. PR-URL: https://github.com/nodejs/node/pull/4803 Reviewed-By: James M Snell --- lib/buffer.js | 8 ++++++-- test/parallel/test-buffer-indexof.js | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index cd4144d886651c..3fb24bef648d48 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -456,10 +456,14 @@ function slowIndexOf(buffer, val, byteOffset, encoding) { } Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - if (byteOffset > 0x7fffffff) + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; - else if (byteOffset < -0x80000000) + } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; + } byteOffset >>= 0; if (typeof val === 'string') { diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 8ed384aea58878..999d6590a9c69d 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -109,6 +109,7 @@ 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); @@ -131,6 +132,21 @@ assert.equal( assert.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')); } +// test optional offset with passed encoding +assert.equal(new Buffer('aaaa0').indexOf('30', 'hex'), 4); +assert.equal(new Buffer('aaaa00a').indexOf('3030', 'hex'), 4); + + +// test usc2 encoding +var twoByteString = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); + +assert.equal(8, twoByteString.indexOf('\u0395', 4, 'ucs2')); +assert.equal(6, twoByteString.indexOf('\u03a3', -4, 'ucs2')); +assert.equal(4, twoByteString.indexOf('\u03a3', -6, 'ucs2')); +assert.equal(4, twoByteString.indexOf( + new Buffer('\u03a3', 'ucs2'), -6, 'ucs2')); +assert.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')); + var mixedByteStringUcs2 = new Buffer('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2'); assert.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2'));