v / examples / cbor.v
78 lines · 68 sloc · 1.89 KB · 468855eef1db0ff73c62be2d1bf176ffa0e1478e
Raw
1module main
2
3import encoding.cbor
4import encoding.hex
5import time
6
7struct Address {
8 street string
9 city string
10 zip string @[cbor: 'postal_code']
11}
12
13struct User {
14 name string
15 age u32
16 email ?string
17 tags []string
18 address Address
19 signed_up time.Time
20 internal string @[skip]
21}
22
23fn main() {
24 user := User{
25 name: 'Alice'
26 age: 30
27 email: '[email protected]'
28 tags: ['admin', 'beta']
29 address: Address{
30 street: '1 Test Lane'
31 city: 'Paris'
32 zip: '75000'
33 }
34 signed_up: time.parse_iso8601('2025-01-15T10:00:00Z') or { time.now() }
35 internal: 'will not be encoded'
36 }
37
38 // 1. Generic typed encode/decode
39 bytes := cbor.encode[User](user, cbor.EncodeOpts{})!
40 println('encoded ${bytes.len} bytes: ${hex.encode(bytes)}')
41
42 back := cbor.decode[User](bytes, cbor.DecodeOpts{})!
43 println('round-trip name=${back.name} age=${back.age} city=${back.address.city}')
44
45 // 2. Canonical encoding for stable hashing/signing
46 mut m := map[string]int{}
47 m['z'] = 26
48 m['a'] = 1
49 m['m'] = 13
50 canonical := cbor.encode[map[string]int](m, cbor.EncodeOpts{
51 canonical: true
52 })!
53 println('canonical map: ${hex.encode(canonical)}')
54
55 // 3. Decode an unknown payload into a Value tree
56 v := cbor.decode[cbor.Value](bytes, cbor.DecodeOpts{})!
57 if name_val := v.get('name') {
58 if s := name_val.as_string() {
59 println('peeked name from Value tree: ${s}')
60 }
61 }
62
63 // 4. Manual streaming: build a CBOR array of mixed types
64 mut p := cbor.new_packer(cbor.EncodeOpts{})
65 p.pack_array_header(3)
66 p.pack_uint(42)
67 p.pack_text('hello')
68 p.pack_bool(true)
69 stream_bytes := p.bytes()
70 println('manual stream: ${hex.encode(stream_bytes)}')
71
72 mut up := cbor.new_unpacker(stream_bytes, cbor.DecodeOpts{})
73 n := up.unpack_array_header()!
74 first := up.unpack_uint()!
75 second := up.unpack_text()!
76 third := up.unpack_bool()!
77 println('unpacked array of ${n}: ${first}, "${second}", ${third}')
78}
79