nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
105.3k stars 28.53k forks source link

Add support to Buffer.indexOf(value, startOffset, endOffset) #51966

Open rentalhost opened 4 months ago

rentalhost commented 4 months ago

What is the problem this feature will solve?

Currently, if you have a task where you need to search for a certain value in a Buffer, you will use .indexOf(). However, if this Buffer is too long and you don't need to search very deeply (like in Yaz0 compression method), you will probably end up searching too deep unnecessarily.

A primary solution is to use .subarray() to limit the maximum search capacity, however, creating a Buffer in this process is much more costly for small and medium-sized files than using .indexOf() even though it has to go to the end of Buffer.

What is the feature you are proposing to solve the problem?

My proposal is to include the possibility of determining how far .indexOf() can search from the current point. The signature would be something like:

Buffer.indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number;
Buffer.indexOf(value: string | number | Uint8Array, byteOffset: number, searchLimit: number, encoding?: BufferEncoding): number;

Then, when the third argument is entered, the search will end if no value element is found in the Buffer in time.

Example:

const buffer = Buffer.from("abcdefg");

console.log(buffer.indexOf("g", 3, 5); // -1

What alternatives have you considered?

So, supporting a limiter in .indexOf() seems interesting to me, mainly to avoid using .subarray() to limit the scope of the search when the limit is known.

jasnell commented 4 months ago

I think the idea is good but I would be wary straying farther from the standard definition of Uint8Array.prototype.indexOf. It would also be nice for this to work with all TypedArrays. So maybe a method on the buffer module instead? e.g. require('buffer').indexOf(buf, value, start, end). Either way, I'm +1 on the general idea

BenzeneAlcohol commented 4 months ago

Is someone interested to work on this issue, or can I take this up?

Uzlopak commented 4 months ago

I am -1 on this. It should be proposed to tsc39. Maybe also proposing this for normal Arrays.

https://github.com/tc39/proposals