buffer icon indicating copy to clipboard operation
buffer copied to clipboard

Buffer.alloc with non-buffer fill

Open timoxley opened this issue 5 years ago • 0 comments

Hi @feross!

If you pass a <Uint8Array> as the fill to Buffer.alloc(size[, fill[, encoding]]) node (v14.15.1) will copy those bytes verbatim into the buffer, whereas with the ferros/buffer package, it does something and the end result is that the resulting buffer is filled with strange data.

const input = [ 247, 108, 225 ]
const typedArr = new Uint8Array(input)
const output = Array.from(Buffer.alloc(typedArr.byteLength, typedArr))

// node:
// [ 247, 108, 225 ] (matches input, expected)

// feross/buffer:
//  [ 239, 191, 189 ] (???)

It works fine for numbers between 0 and 127, but things get weird once you're out of those bounds (Uint8 should work for numbers between 0 - 255).

Workaround is to pass a Buffer as the fill value:

const output = Array.from(Buffer.alloc(typedArr.byteLength, Buffer.from(typedArr)))

// node:
// [ 247, 108, 225 ] (cool)

// feross/buffer:
// [ 247, 108, 225 ] (cool)

I'd perhaps PR a fix for this specific issue, but I feel like the real problem is that this package needs to be refreshed with the latest buffer code + tests from node, rather than me patching in a specific fix? i.e. Perhaps related to #177. I looked into this briefly and the transform from node looked non-trivial if you haven't done it before.

timoxley avatar Dec 08 '20 15:12 timoxley