paroga / cbor-js

The Concise Binary Object Representation (CBOR) data format (RFC7049) implemented in pure JavaScript.
MIT License
310 stars 51 forks source link

Use slice for returrning an Array Buffer #34

Open kion-dgl opened 1 year ago

kion-dgl commented 1 year ago

I ran into this issue when building this example: https://kion-dgl.github.io/three-cbor-loader/ because the model wasn't loading for the CBOR model, but it worked when emulated loading the CBOR model by loading the JSON and putting in ArrayBuffer where they were expected.

The issue turned out to be here: https://github.com/paroga/cbor-js/blob/master/cbor.js#L199

  function readArrayBuffer(length) {
    return commitRead(length, new Uint8Array(data, offset, length));
  }

The problem is that I wanted to work with an ArrayBuffer, not a Uint8Array. So I used cbor.myData.buffer and got the entire CBOR ArrayBuffer back and not the section sliced out that I wanted.

I recommend using ArrayBuffer.slice to only return the section of the CBOR data that corresponds to what the programmer is expecting for that attribute.

  function readArrayBuffer(length) {
    return commitRead(length, data.slice(offset, offset + length));
  }