You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Buffer's indexOf does not seem to handle numbers correctly #7591
Node seems to behave oddly when using indexOf (or includes) on a buffer
It seems that when a string or buffer is the parameter of indexOf it returns the index of the first byte that matches it; however, when a number is passed in it returns the index of the last byte that matched it, unless there are duplicates, then it behaves very oddly.
$ node
> buf = new Buffer('this is a test');
<Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
> buf.indexOf('is') // pass
2
> buf.indexOf(new Buffer('is')) // pass
2
> buf.indexOf(new Buffer('istest')) // pass
-1
> buf.indexOf('istest') // pass
-1
> buf.indexOf(0x6973) // odd
3
> buf.indexOf(0x697320) // appears to return the index of the last byte that matched the number given
4
> buf.indexOf(0x69732069) // unless there are duplicates, then it does weird things
2
> buf.indexOf(0x697374657374)
0
> buf.indexOf(0x69737374)
0
> buf.indexOf(0x69737465)
11
Activity
addaleax commentedon Jul 7, 2016
I think this is the intended behaviour, because
.indexOf()converts the argument to an 8-bit integer, i.e. it truncates0x69737374to0x74.jasnell commentedon Jul 7, 2016
@nodejs/buffer
jasnell commentedon Jul 7, 2016
Yes, this seems to be the correct behavior
test,doc: clarify `buf.indexOf(num)` input range
test,doc: clarify `buf.indexOf(num)` input range
test,doc: clarify `buf.indexOf(num)` input range
test,doc: clarify `buf.indexOf(num)` input range
test,doc: clarify `buf.indexOf(num)` input range
test,doc: clarify `buf.indexOf(num)` input range
test,doc: clarify `buf.indexOf(num)` input range
test,doc: clarify `buf.indexOf(num)` input range
test,doc: clarify `buf.indexOf(num)` input range