pouya-eghbali / sia

Sia - Binary serialisation and deserialisation
131 stars 8 forks source link

Deserialisation fails for nested Maps and Sets #12

Open I-Enderlord-I opened 7 months ago

I-Enderlord-I commented 7 months ago

While both serialisation and deserialisation workds fine if Maps and Sets are only used on top level, the deserialisation throws when they are nested in other objects.

const { desia, sia, DeSia, Sia } = require('sializer');

let obj = new Map();
let buf = sia(obj);
obj = desia(buf); //fine

obj = { k: new Map() };
buf = sia(obj);
obj = desia(buf); //throws string "Key of type 57 is invalid."

This bug is apparently already fixed in the fork by @c7x43t, but that fork does not yet have TypeScript support.

As far as I can tell, the Problem is simply that this.offset in the Deserialiser is not incremented at the end of

      case SIA_TYPES.mapStart: {
        const map = new Map();
        let curr = this.buffer[this.offset];
        while (curr !== SIA_TYPES.mapEnd) {
          map.set(this.readBlock(), this.readBlock());
          curr = this.buffer[this.offset];
        }
        //insert increment here
        return map;
      }

to skip over the SIA_TYPES.mapEnd byte, which is not incremented over before, because it might be the start of the next block. So adding this.offset++; before the return fixes it.

I tried this fix locally for both Map and Set and confirmed that deserialisation works as expected then.

pouya-eghbali commented 7 months ago

@I-Enderlord-I I will make a v1 branch and merge #11 to solve this.