// MessagePack round-trips of a representative nested value (an API // payload: a map of strings, integers, floats, booleans, nulls and a // list of records), ROUNDS times. The size knob is ROUNDS; the checksum // adds up each encoding's length and a fold of what decoding gave back. import std/bytes import std/io import std/list import std/msgpack. {type Value, Array, Bin, Bool, Ext, Float, Int, Map, Nil, Str} import std/string // The round-trip count. fn rounds :: -> Int { 15000 } /// A payload like a list of API records. fn payload :: n: Int -> Value { Map( [ (Str("ok"), Bool(True)) , (Str("page"), Int(3)) , (Str("total"), Int(12345)) , (Str("items"), Array(list.map (list.range 1 n) item)) ] ) } fn item :: i: Int -> Value { Map( [ (Str("id"), Int(i)) , (Str("name"), Str("widget " <> show i)) , (Str("price"), Float(9.99)) , (Str("stock"), Int(i % 5)) , (Str("tags"), Array([Str("a & b"), Str("c")])) , (Str("note"), Nil) ] ) } /// A checksum of a decoded value: 1 per node, plus the bytes of each /// string and the integers' low bits. fn checksum :: v: Value -> Int { match v { Nil -> 1 , Bool(b) -> if b { 2 } else { 1 } , Int(n) -> 1 + n % 65536 , Float(_) -> 1 , Str(s) -> 1 + string.byte_length s , Bin(data) -> 1 + bytes.length data , Array(items) -> list.fold items 1 fn acc x { acc + checksum x } , Map(entries) -> list.fold entries 1 fn acc e { acc + checksum e.0 + checksum e.1 } , Ext(_, data) -> 1 + bytes.length data } } fn round :: value: Value left: Int acc: Int -> Int { if left == 0 { acc } else { let encoded = msgpack.write value match msgpack.read encoded { Ok(decoded) -> round value (left - 1) (acc + bytes.length encoded + checksum decoded) , Error(e) -> panic "msgpack bench: a round trip failed: {show e}" } } } pub fn main :: -> () / { io.println (show (round (payload 20) (rounds ()) 0)) } //> 224325000