kriszyp/cbor-x

cbor-x doesn't support integer keys

mesudip opened this issue · 4 comments

CBOR map keys can be number but this library converts them to string.

As a result encode(decode(data)) != data if there's a number in map.

I wanted to modify a cbor data, but it totally messed up with it.

 [
      {
        '0': [ [Array], [Array] ],
        '1': [ [Array], [Array] ],
        '2': 571741,
        '11': <Buffer 6f d3 c7 48 fa b5 6a 25 59 ba 43 b1 2d 27 1e 36 2c d1 65 19 0d 67 27 b6 6c a3 f4 e0 31 1a d6 44>,
        '13': [ [Array] ]
      },
      {
        '0': [ [Array] ],
        '3': [],
        '5': [ [Array] ],
        '6': [
          <Buffer 59 13 3a 01 00 00 32 32 32 32 33 22 33 22 32 32 32 32 32 33 22 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 33 22 32 32 ... 4875 more bytes>
        ]
      },
      true,
      null
    ]

This wasn't CBOR that messed up your map, it was using JavaScript Object. Objects convert numerical keys to strings. For example:

let obj = {};
obj[0] = 0;
obj[1] = 1;
obj[11] = 11;
console.log(Object.keys(obj)); // all keys are strings
console.log(Object.keys(decode(encode(obj)))); // CBOR exactly duplicates the object string keys

If you want a map that preserves type, you should use... a Map :).

let map = new Map();
map.set(0, 0);
map.set(1, 1);
map.set(11, 11);
console.log([...map.keys()]); // numbers
console.log([...decode(encode(map)).keys()]); // still all numbers

I didn't make that object myself. The object above was created by cbor-x when i decoded some data that had integer in map keys.
Is there a way to tell cbor-x decoder to return Map and not object?

Sure, that's what the mapsAsObjects flag is for, so just disable it like new Decoder({ mapsAsObjects: false }).decode(data).

Thanks. Seems like the configuration I am looking for is like this

const encoder=new Encoder({
  useTag259ForMaps: false

})
const decoder=new Decoder({
  mapsAsObjects: false,
})

But it's weird that cbor-x : 1.5.1 doesn't have the useTag259ForMaps Option despite the docs is saying that it exists.
Is the npm release in sync with the docs?