Skip to content

Commit ea72e9f

Browse files
addaleaxMylesBorins
authored andcommitted
test,doc: clarify buf.indexOf(num) input range
Hopefully clarify the behaviour of `buffer.indexOf()` and `buffer.includes()` for numbers in that they will be truncated to uint8s. Add tests for that behaviour. Fixes: #7591 PR-URL: #7611 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Rich Trott <[email protected]>
1 parent 26e695c commit ea72e9f

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

doc/api/buffer.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -890,7 +890,8 @@ Operates similar to [`Array#indexOf()`][] in that it returns either the
890890
starting index position of `value` in Buffer or `-1` if the Buffer does not
891891
contain `value`. The `value` can be a String, Buffer or Number. Strings are by
892892
default interpreted as UTF8. Buffers will use the entire Buffer (to compare a
893-
partial Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255.
893+
partial Buffer use [`buf.slice()`][]). Numbers will be interpreted as unsigned 8-bit
894+
integer values between `0` and `255`.
894895

895896
```js
896897
const buf = new Buffer('this is a buffer');

test/parallel/test-buffer-indexof.js

+16
Original file line numberDiff line numberDiff line change
@@ -302,3 +302,19 @@ assert.throws(function() {
302302
assert.throws(function() {
303303
b.indexOf([]);
304304
});
305+
306+
// test truncation of Number arguments to uint8
307+
{
308+
const buf = Buffer.from('this is a test');
309+
assert.strictEqual(buf.indexOf(0x6973), 3);
310+
assert.strictEqual(buf.indexOf(0x697320), 4);
311+
assert.strictEqual(buf.indexOf(0x69732069), 2);
312+
assert.strictEqual(buf.indexOf(0x697374657374), 0);
313+
assert.strictEqual(buf.indexOf(0x69737374), 0);
314+
assert.strictEqual(buf.indexOf(0x69737465), 11);
315+
assert.strictEqual(buf.indexOf(0x69737465), 11);
316+
assert.strictEqual(buf.indexOf(-140), 0);
317+
assert.strictEqual(buf.indexOf(-152), 1);
318+
assert.strictEqual(buf.indexOf(0xff), -1);
319+
assert.strictEqual(buf.indexOf(0xffff), -1);
320+
}

0 commit comments

Comments
 (0)