// std/msgpack (issue #140): byte-exact vectors against the MessagePack // specification, round trips of every `Value` shape, decode failures on // untrusted input (truncated, oversize, reserved, too deep), the std // impls of `ToMsgPack`/`FromMsgPack`, and a `@derive(ToMsgPack)` with a // hand-written decoder (until ADR 0051 derives them). import std/array import std/bytes import std/dict import std/int import std/io import std/list import std/msgpack import std/msgpack. {type DecodeError, type FromMsgPack, type ToMsgPack, type Value} import std/result import std/string fn hex :: v: Value -> String { debug (bytes.to_list (msgpack.write v)) } fn show_read :: data: List -> String { debug (msgpack.read (bytes.from_list data)) } fn show_error :: data: Bytes -> String { match msgpack.read data { Ok(v) -> "unexpectedly ok: " <> debug v, Error(e) -> show e } } /// `n` arrays nested around `Int(0)`. fn nest :: n: Int -> Value { if n == 0 { msgpack.Int(0) } else { msgpack.Array([nest (n - 1)]) } } @derive Debug ToMsgPack pub type Order { Order(id: Int, lines: List) } @derive Debug ToMsgPack pub type Shape { Dot, Circle(Int), Rect(Int, Int) } // A hand-written decoder (ADR 0051 derives these): a record is a map // keyed by field label; unknown keys are ignored, a missing field is an // error. impl FromMsgPack { fn from_msgpack :: v { match v { msgpack.Map(fields) -> order_of fields None None , _ -> Error(msgpack.Mismatch("a map for an Order", msgpack.kind v)) } } } fn order_of :: fields: List<(Value, Value)> id: Option lines: Option> -> Result { match fields { [] -> { match (id, lines) { (Some(id), Some(lines)) -> Ok(Order(id, lines)) , _ -> Error( msgpack.Mismatch( "a map with \"id\" and \"lines\"" , "a map without them" ) ) } } , [(key, value), ..rest] -> { match key { msgpack.Str("id") -> { use n <- result.try (msgpack.from_msgpack value) order_of rest Some(n) lines } , msgpack.Str("lines") -> { use ls <- result.try (msgpack.from_msgpack value) order_of rest id Some(ls) } // Unknown keys are ignored (schema evolution). , _ -> order_of rest id lines } } } } pub fn main :: -> () / { // ---- byte-exact vectors: integers, smallest encoding ---------------- io.println (hex msgpack.Nil) io.println (hex msgpack.Bool(False) <> " " <> hex msgpack.Bool(True)) io.println (hex msgpack.Int(0) <> " " <> hex msgpack.Int(127)) io.println (hex msgpack.Int(128) <> " " <> hex msgpack.Int(255)) io.println (hex msgpack.Int(256) <> " " <> hex msgpack.Int(65535)) io.println (hex msgpack.Int(65536) <> " " <> hex msgpack.Int(4294967295)) io.println (hex msgpack.Int(4294967296)) io.println (hex msgpack.Int(int.shift_left 1 64 - 1)) // uint64 max, a big integer io.println (hex msgpack.Int(-1) <> " " <> hex msgpack.Int(-32)) io.println (hex msgpack.Int(-33) <> " " <> hex msgpack.Int(-128)) io.println (hex msgpack.Int(-129) <> " " <> hex msgpack.Int(-32768)) io.println (hex msgpack.Int(-32769) <> " " <> hex msgpack.Int(-2147483648)) io.println (hex msgpack.Int(-2147483649)) io.println (hex msgpack.Int(0 - int.shift_left 1 63)) // int64 min // ---- floats (always float 64; -0.0 keeps its sign bit) --------------- io.println (hex msgpack.Float(1.5)) io.println (hex msgpack.Float(-0.0)) // ---- strings, binary, arrays, maps, ext ------------------------------- io.println (hex msgpack.Str("") <> " " <> hex msgpack.Str("abc")) io.println (hex msgpack.Str("héllo")) // é is two UTF-8 bytes io.println (hex msgpack.Bin(bytes.from_list [0, 255])) io.println ( hex msgpack.Array([]) <> " " <> hex msgpack.Array([msgpack.Int(1), msgpack.Int(2)]) ) io.println ( hex msgpack.Map([]) <> " " <> hex msgpack.Map([(msgpack.Str("a"), msgpack.Int(1))]) ) io.println (hex msgpack.Ext(1, bytes.from_list [255])) // fixext 1 io.println (hex msgpack.Ext(-1, bytes.from_list [0, 0, 0, 0])) // fixext 4, tag -1 // The wider length headers (str 16, array 16, bin 16): header bytes and // total length. let long_str = msgpack.write msgpack.Str(string.repeat "ab" 150) io.println "{bytes.length long_str} {debug (bytes.to_list (bytes.slice long_str 0 3))}" let wide_array = msgpack.write msgpack.Array(list.map (list.range 1 16) fn n { msgpack.Int(n) }) io.println "{bytes.length wide_array} {debug (bytes.to_list (bytes.slice wide_array 0 3))}" let wide_bin = msgpack.write msgpack.Bin(bytes.from_list (list.map (list.range 1 300) fn _ { 7 })) io.println "{bytes.length wide_bin} {debug (bytes.to_list (bytes.slice wide_bin 0 3))}" // ---- reading: every family, widening, big integers -------------------- io.println (show_read [202, 63, 192, 0, 0]) // float 32, widened io.println (show_read [203, 63, 248, 0, 0, 0, 0, 0, 0]) io.println (show_read [207, 255, 255, 255, 255, 255, 255, 255, 255]) // uint64 max io.println (show_read [211, 128, 0, 0, 0, 0, 0, 0, 0]) // int64 min io.println (show_read [204, 0]) // non-minimal encodings decode fine io.println (show_read [217, 3, 97, 98, 99]) io.println (show_read [196, 2, 0, 255]) io.println (show_read [130, 161, 97, 1, 161, 98, 145, 195]) io.println (show_read [199, 3, 254, 1, 2, 3]) // ext 8, tag -2 io.println (show_read [220, 0, 2, 1, 2]) // array 16 // ---- round trips of a corpus ------------------------------------------ let corpus = [ msgpack.Nil , msgpack.Bool(True) , msgpack.Int(0 - int.shift_left 1 63) , msgpack.Int(int.shift_left 1 64 - 1) , msgpack.Float(-0.0) , msgpack.Float(3.14159) , msgpack.Str("héllo, 世界") , msgpack.Bin(bytes.from_list [0, 159, 146, 150]) , msgpack.Array([msgpack.Int(1), msgpack.Array([]), msgpack.Str("x")]) , msgpack.Map( [ ( msgpack.Str("k") , msgpack.Array([msgpack.Int(1), msgpack.Float(2.5)]) ) ] ) , msgpack.Ext(-128, bytes.empty ()) , msgpack.Ext( 127 , bytes.from_list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] ) , nest 100 ] let round_trips = list.fold corpus True fn ok v { ok && msgpack.read (msgpack.write v) == Ok(v) } io.println "round trips: {round_trips}" // ---- untrusted input: errors, never a panic or a huge allocation ------- io.println (show_error (bytes.empty ())) io.println (show_error (bytes.from_list [204])) io.println (show_error (bytes.from_list [193])) io.println (show_error (bytes.from_list [161, 255])) io.println (show_error (bytes.from_list [217, 5, 97])) io.println (show_error (bytes.from_list [221, 255, 255, 255, 255, 1])) io.println (show_error (bytes.from_list [1, 1])) // Nesting is bounded: 512 deep reads back, 513 is an error. io.println (show (msgpack.read (msgpack.write (nest 512)) == Ok(nest 512))) io.println (show_error (msgpack.write (nest 513))) // ---- the traits: encode/decode over the std impls ----------------------- io.println (debug (bytes.to_list (msgpack.encode [1, 2, 3]))) io.println (debug (bytes.to_list (msgpack.encode "héllo"))) io.println (debug (bytes.to_list (msgpack.encode True))) io.println (debug (bytes.to_list (msgpack.encode 2.5))) io.println (debug (bytes.to_list (msgpack.encode (bytes.from_list [1, 2, 3])))) io.println (debug (bytes.to_list (msgpack.encode (array.from_list ["a", "b"])))) io.println (debug (bytes.to_list (msgpack.encode (dict.from_list [("a", 1)])))) let none: Option = None io.println (debug (bytes.to_list (msgpack.encode none))) io.println (debug (bytes.to_list (msgpack.encode Some([1, 2])))) let ok: Result = Ok(1) let no: Result = Error("no") io.println (debug (bytes.to_list (msgpack.encode ok))) io.println (debug (bytes.to_list (msgpack.encode no))) let ints: Result, DecodeError> = msgpack.decode (bytes.from_list [147, 1, 2, 3]) io.println (debug ints) let no_back: Result, DecodeError> = msgpack.decode (msgpack.encode no) io.println (debug no_back) // A whole number decodes as a Float too (many encoders write 1.0 as 1). let one: Result = msgpack.decode (bytes.from_list [1]) io.println (debug one) // A mismatch names what was expected and what was found. let not_ints: Result, DecodeError> = msgpack.decode (bytes.from_list [145, 160]) io.println match not_ints { Ok(v) -> "unexpectedly ok: " <> debug v, Error(e) -> show e } // ---- the derive: records as maps, sums tagged by name ------------------- let order = Order(7, ["a", "b"]) io.println (debug (bytes.to_list (msgpack.encode order))) io.println (debug (bytes.to_list (msgpack.encode [Dot, Circle(3), Rect(1, 2)]))) let order_back: Result = msgpack.decode (msgpack.encode order) io.println (debug order_back) // Unknown keys are ignored; a missing field is an error. let extra_map = msgpack.Map( [ (msgpack.Str("id"), msgpack.Int(7)) , ( msgpack.Str("lines") , msgpack.Array([msgpack.Str("a"), msgpack.Str("b")]) ) , (msgpack.Str("future"), msgpack.Nil) ] ) let evolved: Result = msgpack.decode (msgpack.write extra_map) io.println (debug evolved) let missing: Result = msgpack.decode (msgpack.write msgpack.Map([(msgpack.Str("id"), msgpack.Int(7))])) io.println match missing { Ok(v) -> "unexpectedly ok: " <> debug v, Error(e) -> show e } } //> [192] //> [194] [195] //> [0] [127] //> [204, 128] [204, 255] //> [205, 1, 0] [205, 255, 255] //> [206, 0, 1, 0, 0] [206, 255, 255, 255, 255] //> [207, 0, 0, 0, 1, 0, 0, 0, 0] //> [207, 255, 255, 255, 255, 255, 255, 255, 255] //> [255] [224] //> [208, 223] [208, 128] //> [209, 255, 127] [209, 128, 0] //> [210, 255, 255, 127, 255] [210, 128, 0, 0, 0] //> [211, 255, 255, 255, 255, 127, 255, 255, 255] //> [211, 128, 0, 0, 0, 0, 0, 0, 0] //> [203, 63, 248, 0, 0, 0, 0, 0, 0] //> [203, 128, 0, 0, 0, 0, 0, 0, 0] //> [160] [163, 97, 98, 99] //> [166, 104, 195, 169, 108, 108, 111] //> [196, 2, 0, 255] //> [144] [146, 1, 2] //> [128] [129, 161, 97, 1] //> [212, 1, 255] //> [214, 255, 0, 0, 0, 0] //> 303 [218, 1, 44] //> 19 [220, 0, 16] //> 303 [197, 1, 44] //> Ok(Float(1.5)) //> Ok(Float(1.5)) //> Ok(Int(18446744073709551615)) //> Ok(Int(-9223372036854775808)) //> Ok(Int(0)) //> Ok(Str("abc")) //> Ok(Bin(b"\x00\xff")) //> Ok(Map([(Str("a"), Int(1)), (Str("b"), Array([Bool(True)]))])) //> Ok(Ext { tag: -2, data: b"\x01\x02\x03" }) //> Ok(Array([Int(1), Int(2)])) //> round trips: True //> invalid MessagePack at byte 0: the input ends early //> invalid MessagePack at byte 1: a length of 1 with 0 bytes left //> invalid MessagePack at byte 0: 0xc1 is not a MessagePack byte //> invalid MessagePack at byte 1: a str that is not UTF-8: invalid UTF-8 at byte 0 //> invalid MessagePack at byte 2: a length of 5 with 1 bytes left //> invalid MessagePack at byte 5: an array of 4294967295 items with 1 bytes left //> invalid MessagePack at byte 1: 1 bytes after the value //> True //> invalid MessagePack at byte 513: nesting deeper than 512 levels //> [147, 1, 2, 3] //> [166, 104, 195, 169, 108, 108, 111] //> [195] //> [203, 64, 4, 0, 0, 0, 0, 0, 0] //> [196, 3, 1, 2, 3] //> [146, 161, 97, 161, 98] //> [129, 161, 97, 1] //> [192] //> [146, 1, 2] //> [129, 162, 79, 107, 145, 1] //> [129, 165, 69, 114, 114, 111, 114, 145, 162, 110, 111] //> Ok([1, 2, 3]) //> Ok(Error("no")) //> Ok(1.0) //> MessagePack: expected an Int, found a Str //> [130, 162, 105, 100, 7, 165, 108, 105, 110, 101, 115, 146, 161, 97, 161, 98] //> [147, 163, 68, 111, 116, 129, 166, 67, 105, 114, 99, 108, 101, 145, 3, 129, 164, 82, 101, 99, 116, 146, 1, 2] //> Ok(Order { id: 7, lines: ["a", "b"] }) //> Ok(Order { id: 7, lines: ["a", "b"] }) //> MessagePack: expected a map with "id" and "lines", found a map without them