Skip to content

Commit 85e06a2

Browse files
trevnorrisMyles Borins
authored and
Myles Borins
committed
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: #4803 Reviewed-By: James M Snell <[email protected]>
1 parent fe893a8 commit 85e06a2

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

lib/buffer.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -456,10 +456,14 @@ function slowIndexOf(buffer, val, byteOffset, encoding) {
456456
}
457457

458458
Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
459-
if (byteOffset > 0x7fffffff)
459+
if (typeof byteOffset === 'string') {
460+
encoding = byteOffset;
461+
byteOffset = 0;
462+
} else if (byteOffset > 0x7fffffff) {
460463
byteOffset = 0x7fffffff;
461-
else if (byteOffset < -0x80000000)
464+
} else if (byteOffset < -0x80000000) {
462465
byteOffset = -0x80000000;
466+
}
463467
byteOffset >>= 0;
464468

465469
if (typeof val === 'string') {

test/parallel/test-buffer-indexof.js

+16
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ assert.equal(
109109
assert.equal(
110110
Buffer(b.toString('binary'), 'binary')
111111
.indexOf(Buffer('d', 'binary'), 0, 'binary'), 3);
112+
112113
assert.equal(
113114
Buffer('aa\u00e8aa', 'binary')
114115
.indexOf('\u00e8', 'binary'), 2);
@@ -131,6 +132,21 @@ assert.equal(
131132
assert.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2'));
132133
}
133134

135+
// test optional offset with passed encoding
136+
assert.equal(new Buffer('aaaa0').indexOf('30', 'hex'), 4);
137+
assert.equal(new Buffer('aaaa00a').indexOf('3030', 'hex'), 4);
138+
139+
140+
// test usc2 encoding
141+
var twoByteString = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
142+
143+
assert.equal(8, twoByteString.indexOf('\u0395', 4, 'ucs2'));
144+
assert.equal(6, twoByteString.indexOf('\u03a3', -4, 'ucs2'));
145+
assert.equal(4, twoByteString.indexOf('\u03a3', -6, 'ucs2'));
146+
assert.equal(4, twoByteString.indexOf(
147+
new Buffer('\u03a3', 'ucs2'), -6, 'ucs2'));
148+
assert.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2'));
149+
134150
var mixedByteStringUcs2 =
135151
new Buffer('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2');
136152
assert.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2'));

0 commit comments

Comments
 (0)