v / vlib / encoding / cbor / marshaler.v
31 lines · 29 sloc · 849 bytes · 468855eef1db0ff73c62be2d1bf176ffa0e1478e
Raw
1module cbor
2
3// Marshaler lets a user type control its own CBOR encoding. Returned
4// bytes must be exactly one well-formed CBOR data item — the generic
5// encoder copies them verbatim, so malformed output corrupts the
6// surrounding stream.
7//
8// Example:
9//
10// struct Ipv4 { mut: octets [4]u8 }
11//
12// pub fn (ip Ipv4) to_cbor() []u8 {
13// mut p := cbor.new_packer(cbor.EncodeOpts{})
14// p.pack_bytes(ip.octets[..])
15// return p.bytes().clone()
16// }
17pub interface Marshaler {
18 to_cbor() []u8
19}
20
21// Unmarshaler is the reverse: given the bytes of one CBOR data item,
22// populate the receiver. The slice is already trimmed to exactly one
23// item by the generic decoder.
24//
25// Implementers use a mut receiver:
26//
27// pub fn (mut ip Ipv4) from_cbor(data []u8) ! { ... }
28pub interface Unmarshaler {
29mut:
30 from_cbor(data []u8) !
31}
32