Something went wrong. Try again.
Ron's Dynamic EDitor
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462package msgpack
import "core:encoding/endian"import "core:mem"import vmem "core:mem/virtual"import "core:testing"
Decode_Error :: enum { None, Bad_Format, Too_Deep, Out_Of_Memory,}
Token :: union { Nil, bool, i64, u64, f32, f64, Str_Header, Bin_Header, Ext_Header, Array_Header, Map_Header, Chunk,}
Str_Header :: struct { len: int,}
Bin_Header :: struct { len: int,}
Ext_Header :: struct { type: i8, len: int,}
Array_Header :: struct { len: int,}
Map_Header :: struct { len: int,}
// A borrowed chunk of the payload of the last str, bin or ext headerChunk :: distinct []byte
MAX_OBJECT_DEPTH :: 32
Decoder :: struct { stack: [MAX_OBJECT_DEPTH]Stack_Frame, depth: int,
payload: []byte, // currently decoded object's payload payload_remaining: int, // remaining bytes in `payload`}
@(private)Stack_Frame :: struct { slots: []Object, pos: int,}
@(require_results)decode_token :: proc "contextless" (d: ^Decoder, data: ^[]byte) -> (tok: Token, ok: bool, err: Decode_Error) { buf := data^ if d.payload_remaining > 0 { if len(buf) == 0 {return} n := min(len(buf), d.payload_remaining) d.payload_remaining -= n data^ = buf[n:] return Chunk(buf[:n]), true, .None } if len(buf) == 0 {return}
b := buf[0] size := marker_size(b) if size == 0 {return nil, false, .Bad_Format} if len(buf) < size {return} hdr := buf[1:size]
// https://github.com/msgpack/msgpack/blob/master/spec.md - Overview switch { case b <= 0x7f: tok = i64(b) // positive fixint case b <= 0x8f: tok = Map_Header{int(b & 0x0f)} // fixmap case b <= 0x9f: tok = Array_Header{int(b & 0x0f)} // fixarray case b <= 0xbf: tok = Str_Header{int(b & 0x1f)} // fixstr case b >= 0xe0: tok = i64(i8(b)) // negative fixint case: switch Marker(b) { case .Reserved: return nil, false, .Bad_Format case .Nil: tok = Nil{} case .False, .True: tok = b == u8(Marker.True) case .Bin_8: tok = Bin_Header{int(hdr[0])} case .Bin_16: n, nok := endian.get_u16(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = Bin_Header{int(n)} case .Bin_32: n, nok := endian.get_u32(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = Bin_Header{int(n)} case .Ext_8: tok = Ext_Header{i8(hdr[1]), int(hdr[0])} case .Ext_16: n, nok := endian.get_u16(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = Ext_Header{i8(hdr[2]), int(n)} case .Ext_32: n, nok := endian.get_u32(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = Ext_Header{i8(hdr[4]), int(n)} case .Float_32: n, nok := endian.get_f32(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = n case .Float_64: n, nok := endian.get_f64(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = n case .Uint_8: tok = i64(hdr[0]) case .Uint_16: n, nok := endian.get_u16(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = i64(n) case .Uint_32: n, nok := endian.get_u32(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = i64(n) case .Uint_64: u, nok := endian.get_u64(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = u if u > u64(max(i64)) else i64(u) case .Int_8: tok = i64(i8(hdr[0])) case .Int_16: n, nok := endian.get_u16(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = i64(i16(n)) case .Int_32: n, nok := endian.get_u32(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = i64(i32(n)) case .Int_64: n, nok := endian.get_u64(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = i64(n) case .Fix_Ext_1 ..= .Fix_Ext_16: tok = Ext_Header{i8(hdr[0]), 1 << (b - u8(Marker.Fix_Ext_1))} // fixext 1, 2, 4, 8, 16 case .Str_8: tok = Str_Header{int(hdr[0])} case .Str_16: n, nok := endian.get_u16(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = Str_Header{int(n)} case .Str_32: n, nok := endian.get_u32(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = Str_Header{int(n)} case .Array_16: n, nok := endian.get_u16(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = Array_Header{int(n)} case .Array_32: n, nok := endian.get_u32(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = Array_Header{int(n)} case .Map_16: n, nok := endian.get_u16(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = Map_Header{int(n)} case .Map_32: n, nok := endian.get_u32(hdr, .Big) if !nok {return nil, false, .Bad_Format} tok = Map_Header{int(n)} } }
// https://github.com/msgpack/msgpack/blob/master/spec.md - str, bin and ext format families #partial switch t in tok { case Str_Header: d.payload_remaining = t.len case Bin_Header: d.payload_remaining = t.len case Ext_Header: d.payload_remaining = t.len } data^ = buf[size:] return tok, true, .None}
@(require_results)decode_object :: proc( d: ^Decoder, data: ^[]byte, out: ^Object, allocator: mem.Allocator,) -> ( done: bool, err: Decode_Error,) { loop: for { tok, ok := decode_token(d, data) or_return if !ok {return false, .None}
slot := out if d.depth > 0 { frame := &d.stack[d.depth - 1] slot = &frame.slots[frame.pos] }
// https://github.com/msgpack/msgpack/blob/master/spec.md - Deserialization: format to type conversion switch tok in tok { case Nil: slot^ = tok case bool: slot^ = tok case i64: slot^ = tok case u64: slot^ = tok case f32: slot^ = tok case f64: slot^ = tok case Str_Header: buf := decoder_alloc(byte, tok.len, allocator) or_return slot^ = string(buf) if d.payload = buf; len(buf) > 0 {continue} case Bin_Header: buf := decoder_alloc(byte, tok.len, allocator) or_return slot^ = Bin(buf) if d.payload = buf; len(buf) > 0 {continue} case Ext_Header: buf := decoder_alloc(byte, tok.len, allocator) or_return slot^ = Ext{tok.type, buf} if d.payload = buf; len(buf) > 0 {continue} case Array_Header: items := decoder_alloc(Object, tok.len, allocator) or_return slot^ = Array(items) if decoder_push_slots(d, items) or_return {continue} case Map_Header: pairs := decoder_alloc(Map_Pair, tok.len, allocator) or_return slot^ = Map(pairs) if decoder_push_slots(d, mem.slice_data_cast([]Object, pairs)) or_return {continue} case Chunk: dst := d.payload[len(d.payload) - d.payload_remaining - len(tok):] copy(dst, ([]byte)(tok)) if d.payload_remaining > 0 {continue} }
// Done decoding. Make sure we close all parent objects up the stack for d.depth > 0 { frame := &d.stack[d.depth - 1] frame.pos += 1 if frame.pos < len(frame.slots) {continue loop} // This stack frame still needs decoding d.depth -= 1 }
return true, .None }}
// The array/map just decoded has n slots to fill.@(private)decoder_push_slots :: proc "contextless" (d: ^Decoder, slots: []Object) -> (bool, Decode_Error) { if len(slots) == 0 {return false, .None} if d.depth == MAX_OBJECT_DEPTH {return false, .Too_Deep} d.stack[d.depth] = {slots, 0} d.depth += 1 return true, .None}
@(private)decoder_alloc :: proc($T: typeid, n: int, allocator: mem.Allocator) -> ([]T, Decode_Error) { s, err := make([]T, n, allocator) if err != nil {return nil, .Out_Of_Memory} return s, .None}
// Used for testing.//// `bytes` are the bytes to decode.// Pieces are the parts (in byte lengths) of the bytes that are simulated to be streamed separately.// Pieces can be `nil` to not split `bytes` into parts@(private)test_decode :: proc( bytes: []byte, pieces: []int = nil, allocator := context.temp_allocator,) -> ( object: Object, ok: bool, err: Decode_Error,) { d: Decoder buf: [dynamic]byte defer delete(buf) from := 0 for i in 0 ..= len(pieces) { to := pieces[i] if i < len(pieces) else len(bytes) append(&buf, ..bytes[from:to]) from = to data := buf[:] done := decode_object(&d, &data, &object, allocator) or_return remove_range(&buf, 0, len(buf) - len(data)) if done {return object, len(buf) == 0 && from == len(bytes), .None} } return}
@(private)Golden :: struct { object: Object, bytes: []byte,}
@(private)GOLDEN := [?]Golden { // Named markers are spelled with their Marker. Markers that pack their payload into the low bits // (positive and negative fixint, fixstr, fixarray, fixmap) cover ranges, so they stay raw bytes. {Nil{}, {u8(Marker.Nil)}}, {false, {u8(Marker.False)}}, {true, {u8(Marker.True)}}, // positive fixint, uint 8/16/32/64 {i64(0), {0x00}}, {i64(max(i8)), {0x7f}}, {i64(max(i8)) + 1, {u8(Marker.Uint_8), 0x80}}, {i64(max(u8)), {u8(Marker.Uint_8), 0xff}}, {i64(max(u8)) + 1, {u8(Marker.Uint_16), 0x01, 0x00}}, {i64(max(u16)), {u8(Marker.Uint_16), 0xff, 0xff}}, {i64(max(u16)) + 1, {u8(Marker.Uint_32), 0x00, 0x01, 0x00, 0x00}}, {i64(max(u32)), {u8(Marker.Uint_32), 0xff, 0xff, 0xff, 0xff}}, {i64(max(u32)) + 1, {u8(Marker.Uint_64), 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00}}, {max(i64), {u8(Marker.Uint_64), 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {max(u64), {u8(Marker.Uint_64), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, // negative fixint, int 8/16/32/64 {i64(-1), {0xff}}, {i64(-32), {0xe0}}, {i64(-33), {u8(Marker.Int_8), 0xdf}}, {i64(min(i8)), {u8(Marker.Int_8), 0x80}}, {i64(min(i8)) - 1, {u8(Marker.Int_16), 0xff, 0x7f}}, {i64(min(i16)), {u8(Marker.Int_16), 0x80, 0x00}}, {i64(min(i16)) - 1, {u8(Marker.Int_32), 0xff, 0xff, 0x7f, 0xff}}, {i64(min(i32)), {u8(Marker.Int_32), 0x80, 0x00, 0x00, 0x00}}, {i64(min(i32)) - 1, {u8(Marker.Int_64), 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff}}, {min(i64), {u8(Marker.Int_64), 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, // float32/64 {f32(1.5), {u8(Marker.Float_32), 0x3f, 0xc0, 0x00, 0x00}}, {f64(1.5), {u8(Marker.Float_64), 0x3f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, // fixstr, str 8, bin 8, fixext, ext 8 {"", {0xa0}}, {"abc", {0xa3, 'a', 'b', 'c'}}, {"€!", {0xa4, 0xe2, 0x82, 0xac, '!'}}, {Bin{}, {u8(Marker.Bin_8), 0x00}}, {Bin{1, 2}, {u8(Marker.Bin_8), 0x02, 0x01, 0x02}}, {Ext{5, {9}}, {u8(Marker.Fix_Ext_1), 0x05, 0x09}}, {Ext{-1, {1, 2}}, {u8(Marker.Fix_Ext_2), 0xff, 0x01, 0x02}}, {Ext{2, {1, 2, 3, 4}}, {u8(Marker.Fix_Ext_4), 0x02, 1, 2, 3, 4}}, {Ext{3, {1, 2, 3, 4, 5, 6, 7, 8}}, {u8(Marker.Fix_Ext_8), 0x03, 1, 2, 3, 4, 5, 6, 7, 8}}, { Ext{4, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}}, {u8(Marker.Fix_Ext_16), 0x04, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, }, {Ext{5, {1, 2, 3}}, {u8(Marker.Ext_8), 0x03, 0x05, 0x01, 0x02, 0x03}}, {Ext{5, {}}, {u8(Marker.Ext_8), 0x00, 0x05}}, // fixarray, array 16, fixmap, map 16 {Array{}, {0x90}}, {Array{i64(1), "a"}, {0x92, 0x01, 0xa1, 'a'}}, { Array{Nil{}, Nil{}, Nil{}, Nil{}, Nil{}, Nil{}, Nil{}, Nil{}, Nil{}, Nil{}, Nil{}, Nil{}, Nil{}, Nil{}, Nil{}}, // fixarray 15, then 15 nils: raw to keep the row on one line {0x9f, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0}, }, { Array { i64(0), i64(1), i64(2), i64(3), i64(4), i64(5), i64(6), i64(7), i64(8), i64(9), i64(10), i64(11), i64(12), i64(13), i64(14), i64(15), }, {u8(Marker.Array_16), 0x00, 0x10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, }, {Map{}, {0x80}}, {Map{{"a", i64(1)}}, {0x81, 0xa1, 'a', 0x01}}, {Map{{Array{i64(1)}, Map{{i64(2), i64(3)}}}}, {0x81, 0x91, 0x01, 0x81, 0x02, 0x03}}, // [[], {"k": [nil, {}]}, "z"] { Array{Array{}, Map{{"k", Array{Nil{}, Map{}}}}, "z"}, {0x93, 0x90, 0x81, 0xa1, 'k', 0x92, u8(Marker.Nil), 0x80, 0xa1, 'z'}, },}
@(test)test_golden :: proc(t: ^testing.T) { arena: vmem.Arena defer vmem.arena_destroy(&arena) allocator := vmem.arena_allocator(&arena)
for g in GOLDEN { // all obj, ok, err := test_decode(g.bytes, allocator = allocator) testing.expectf(t, ok && object_equals(obj, g.object), "% x: got %v %v, want %v", g.bytes, obj, err, g.object)
// split and truncation for piece in 0 ..< len(g.bytes) { obj, ok, err = test_decode(g.bytes, pieces = {piece}, allocator = allocator) testing.expectf( t, ok && object_equals(obj, g.object), "% x piece at %d: got %v %v", g.bytes, piece, obj, err, )
d: Decoder out: Object data := g.bytes[:piece] done, terr := decode_object(&d, &data, &out, allocator) testing.expectf(t, !done && terr == .None, "% x truncated to %d: %v %v", g.bytes, piece, done, terr) }
// byte-by-byte pieces := make([]int, max(len(g.bytes) - 1, 0), context.temp_allocator) for &c, i in pieces {c = i + 1} obj, ok, err = test_decode(g.bytes, pieces = pieces, allocator = allocator) testing.expectf(t, ok && object_equals(obj, g.object), "% x a byte at a time: got %v %v", g.bytes, obj, err)
vmem.arena_free_all(&arena) }}