Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Codec option to encode Uint8Array like ArrayBuffer #89

Open
dbrgn opened this issue May 17, 2018 · 3 comments
Open

Codec option to encode Uint8Array like ArrayBuffer #89

dbrgn opened this issue May 17, 2018 · 3 comments

Comments

@dbrgn
Copy link

dbrgn commented May 17, 2018

Currently, with the binarybuffer option, ArrayBuffer instances are converted to bin bytes.

>>> msgpack.encode(Uint8Array.of(1,2,3,4).buffer, { codec: msgpack.createCodec({ binarraybuffer: true }) })
Uint8Array [ 196, 4, 1, 2, 3, 4 ]

However, when passing an Uint8Array directly, it gets converted to a map (or to an extension type when turning on the preset):

>>> msgpack.encode(Uint8Array.of(1,2,3,4), { codec: msgpack.createCodec({ binarraybuffer: true }) })
Uint8Array [ 132, 161, 48, 1, 161, 49, 2, 161, 50, 3, … ]

Could you maybe add an option to treat an UInt8Array like an ArrayBuffer when encoding?

@dbrgn
Copy link
Author

dbrgn commented Jul 23, 2018

Advanage of properly handling Uint8Array as bin type: When you have a Uint8Array which is a view into an ArrayBuffer, then you cannot simply pass u8a.buffer to msgpack, since then the byteOffset and byteLength will be lost. The only way to properly encode the data is to copy it into a new ArrayBuffer like so:

const start = decryptedBytes.byteOffset;
const end = start + decryptedBytes.byteLength;
return decryptedBytes.buffer.slice(start, end);

This copying is unnecessary. It would be better if a Uint8Array (which is a view into a buffer) could be serialized directly.

@lgrahl
Copy link

lgrahl commented Jul 23, 2018

In addition, the decoding function could hand out a view into the original buffer which will also be much more efficient.

@MeirionHughes
Copy link

I'd be in favor of Uint8Array, ArrayBuffer and Buffer being encoded to 'bin', but bin decoded to Uint8Array by default. that would likely need a major version bump, but it would mean not needing Buffer in the browser. node's Buffer is an Uint8Array under the hood anyway I believe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants