xtpor / godot-msgpack

A MessagePack serializer implemented in pure GDScript / msgpack.org[GDScript]
33 stars 6 forks source link

128 converts to -128; Problem with signed integers #3

Open Taobis opened 1 year ago

Taobis commented 1 year ago

There seems to be some trouble with signed and unsigned on integers. I see you only use signed integers for encoding. But if the number is 128 or 32768 it seems to wrap around and i get -128 and -32768.

This is in Godot 4 actually, but the bug also exists in godot 3. I changed the int-section on func _encode to fix it:

    TYPE_INT:
        if value >= 0:
            if value < 128:
                buf.put_u8(value)
            elif value <= 0xff :
                buf.put_u8(0xcc)
                buf.put_u8(value)
            elif value <= 0xffff:
                buf.put_u8(0xcd)
                buf.put_u16(value)
            elif value <= 0xffffffff:
                buf.put_u8(0xce)
                buf.put_u32(value)
            else:
                buf.put_u8(0xcf)
                buf.put_u64(value)

        else:
            if value >= -32 :
                buf.put_u8(0xe0 + (value + 32))
            elif value >= -128 :
                buf.put_u8(0xd0)
                buf.put_8(value)
            elif value >= -32768 :
                buf.put_u8(0xd1)
                buf.put_16(value)
            elif value >= -2147483648 :
                buf.put_u8(0xd2)
                buf.put_32(value)
            else:
                buf.put_u8(0xd3)
                buf.put_64(value)

I quickly tested it and it seems to work good so far.