iwoplaza / typed-binary

Describe binary structures with full TypeScript support. Encode and decode into pure JavaScript objects.
https://iwoplaza.github.io/typed-binary/
MIT License
106 stars 3 forks source link

BufferWriter.writeSlice() ignores Uint8Array length #35

Closed cyraxx closed 1 month ago

cyraxx commented 2 months ago

BufferWriter.writeSlice() calls unwrapBuffer() to get its own view of the underlying buffer. However, this only takes into account the byteOffset and not the byteLength. So it always creates its view all the way to the end of the underlying buffer.

Example to reproduce the issue:

// Create a 2000 byte ArrayBuffer.
const someBuffer = new ArrayBuffer(2000);

// Create a 100 byte Uint8Array view into the ArrayBuffer at offset 10.
const someView = new Uint8Array(someBuffer, 10, 100);
console.log(`Should write ${someView.length} bytes`);

// Write the Uint8Array into a BufferWriter.
console.log(`Position before writing: ${output.currentByteOffset}`);
output.writeSlice(someView);
console.log(`Position after writing: ${output.currentByteOffset}`);

This will show that 1990 bytes have been written to the output instead of just 100.

iwoplaza commented 2 months ago

Thank you for reporting the issue! Definitely looks like this should not be happening. I will get to fixing it promptly and include it as 4.1.1 patch release. I will also include your minimal reproduction as a test case so we do not see it reappear as a regression.

iwoplaza commented 1 month ago

Just included the fix in v4.1.1, available via NPM. Thanks again for the report! 💚