kriszyp / cbor-x

Ultra-fast CBOR encoder/decoder with extensions for records and structural cloning
MIT License
276 stars 32 forks source link

Sort record keys #49

Open atomictag opened 2 years ago

atomictag commented 2 years ago

Currently

    const obj1 = { a: "A", b: "B", c: "C" };
    const obj2 = { c: "C", b: "B", a: "A" };

serialize to different CBOR bytes because keys are sorted differently (although the objects are deep-equal).

I'm not sure what the specs say in this regard, but it would be very useful to have the possibility (perhaps via an option flag) to get record keys sorted lexicographically so that equal objects would produce the same octet stream. This could be useful in a number of contexts - e.g. signatures, hashing...

It could be something as trivial as

Object.keys(record)
.sort()
.reduce((obj, key) => {
   obj[key] = record[key];
   return obj;
 }, {});
kriszyp commented 2 years ago

Do you think it would work just as well to do this lexicographic sorting before submitting the object(s) to cbor-x?

atomictag commented 2 years ago

Do you think it would work just as well to do this lexicographic sorting before submitting the object(s) to cbor-x?

That's actually what I am currently doing and it works well. The order of JavaScript properties is guaranteed to be preserved since (I believe) ES2015. However this is more a food-for-thoughts and a nice-to-have than an issue with cbor-x per-se - it would just be handy if serialized records followed some key-sorting rule in order to make the CBOR output deterministic given an equal set of record inputs where the order of keys may be different.