nodejs / node

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

Buffer created from Buffer.from gives wrong length #34570

Open dsandber opened 4 years ago

dsandber commented 4 years ago

What steps will reproduce the bug?

let a=new Uint8Array(10); let b=Buffer.from(a,0,5); console.log(a.length); (prints 10) console.log(b.length); (prints 10, expected 5)

If a.buffer is passed in, the correct result is given.

Either the expected result should occur (5), or a TypeError should be thrown since otherwise a very counter-intuitive result is given.

How often does it reproduce? Is there a required condition?

What is the expected behavior?

What do you see instead?

Additional information

addaleax commented 4 years ago

Throwing a TypeError when too many arguments are being passed is a bit unusual in JS, but I think that would be okay here since I could see how this behaviour would indeed be surprising in practice.

dsandber commented 4 years ago

Given that Buffer.from(UInt8Array) is supported, why not make so the function that supports offset and length also works with UInt8Array?

And more generally, is the issue that the "offset" and "length" would not be clearly defined for TypedArrays whose members are bigger than a byte?

addaleax commented 4 years ago

And more generally, is the issue that the "offset" and "length" would not be clearly defined for TypedArrays whose members are bigger than a byte?

Yes, I would say so. Buffer.from(buffer) is listed separately in the docs with the intention of making things clearer, but it’s not implemented differently from Buffer.from(array) (or generally any object with a length property). If we do add support for more arguments, I would prefer going the Uint8Array.from() route, because Buffer inherits from Uint8Array.