tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

81 lignes · 1980 octetsBrut · Historique
1// MessagePack round-trips of a representative nested value (an API
2// payload: a map of strings, integers, floats, booleans, nulls and a
3// list of records), ROUNDS times. The size knob is ROUNDS; the checksum
4// adds up each encoding's length and a fold of what decoding gave back.
5
6import std/bytes
7import std/io
8import std/list
9import std/msgpack.
10{type Value, Array, Bin, Bool, Ext, Float, Int, Map, Nil, Str}
11import std/string
12
13// The round-trip count.
14fn rounds :: -> Int
15{
16 15000
17}
18
19/// A payload like a list of API records.
20fn payload :: n: Int -> Value
21{
22 Map( [ (Str("ok"), Bool(True))
23 , (Str("page"), Int(3))
24 , (Str("total"), Int(12345))
25 , (Str("items"), Array(list.map (list.range 1 n) item))
26 ]
27 )
28}
29
30fn item :: i: Int -> Value
31{
32 Map( [ (Str("id"), Int(i))
33 , (Str("name"), Str("widget " <> show i))
34 , (Str("price"), Float(9.99))
35 , (Str("stock"), Int(i % 5))
36 , (Str("tags"), Array([Str("a & b"), Str("c")]))
37 , (Str("note"), Nil)
38 ]
39 )
40}
41
42/// A checksum of a decoded value: 1 per node, plus the bytes of each
43/// string and the integers' low bits.
44fn checksum :: v: Value -> Int
45{
46 match v
47 { Nil -> 1
48 , Bool(b) -> if b { 2 } else { 1 }
49 , Int(n) -> 1 + n % 65536
50 , Float(_) -> 1
51 , Str(s) -> 1 + string.byte_length s
52 , Bin(data) -> 1 + bytes.length data
53 , Array(items) -> list.fold items 1 fn acc x { acc + checksum x }
54 , Map(entries) ->
55 list.fold entries 1 fn acc e { acc + checksum e.0 + checksum e.1 }
56 , Ext(_, data) -> 1 + bytes.length data
57 }
58}
59
60fn round :: value: Value left: Int acc: Int -> Int
61{
62 if left == 0
63 {
64 acc
65 }
66 else
67 {
68 let encoded = msgpack.write value
69 match msgpack.read encoded
70 { Ok(decoded) ->
71 round value (left - 1) (acc + bytes.length encoded + checksum decoded)
72 , Error(e) -> panic "msgpack bench: a round trip failed: {show e}"
73 }
74 }
75}
76
77pub fn main :: -> () / <io>
78{
79 io.println (show (round (payload 20) (rounds ()) 0))
80}
81//> 224325000