buffer
buffer copied to clipboard
lastIndexOf: fix byteOffset when encoding passed as second arg
Currently, buffer.lastIndexOf behaves differently than node's Buffer when encoding is passed as second argument.
To reproduce the issue :
> node -e "console.log(require('node:buffer').Buffer.from('abcdef').lastIndexOf('b', 'utf8'))"
1
> node -e "console.log(require('buffer/').Buffer.from('abcdef').lastIndexOf('b', 'utf8'))"
-1
The problem comes from the fact that, in bidirectionalIndexOf, when typeof byteOffset === 'string, the code sets byteOffset = 0. This is perfectly fine for indexOf, but breaks lastIndexOf (as the correct value would be the end of the buffer).
This PR fixes this, by setting byteOffset = undefined instead (this is what NodeJS does : https://github.com/nodejs/node/blob/main/lib/buffer.js#L980 ). It also adds a test for this.