hildjj / node-cbor

Encode and decode CBOR documents, with both easy mode, streaming mode, and SAX-style evented mode.
MIT License
357 stars 73 forks source link

How to decodeFirst while ignoring extra data? #118

Closed mcclure closed 3 years ago

mcclure commented 3 years ago

The doc for decodeFirst says, my emphasis:

Decode the first CBOR item in the input. This will error if there are more bytes left over at the end

Several things are confusing me.

Given all this, my questions:

mcclure commented 3 years ago

Testing, I fed an ArrayBufferView containing [one CBOR item and then extra bytes] to decodeFirst. I still don't know how to decode an item and then get the index following the decoded item, but it does appear the claim in the decodeFirst docs "This will error if there are more bytes left over at the end" is incorrect. I did not get an error.

hildjj commented 3 years ago

I also fixed the docs to make it clear that both decodeFirst and decodeFirstSync will throw errors if there is extra data and you haven't specified {extendedResults: true}.

I'll do a release tomorrow if you agree this fixes your issue.

hildjj commented 3 years ago

Example:

cbor.decodeFirstSync('6161f6', {extendedResults: true})
// { value: 'a', bytes: <Buffer 61 61>, length: 2, unused: <Buffer f6> }
hildjj commented 3 years ago

this is in 6.0.1

mcclure commented 3 years ago

This is great, thank you, I think this is exactly what I needed, I might not have time to test it for a bit tho