buffer icon indicating copy to clipboard operation
buffer copied to clipboard

lastIndexOf: fix byteOffset when encoding passed as second arg

Open arantes555 opened this issue 8 months ago • 0 comments

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.

arantes555 avatar Mar 14 '25 10:03 arantes555