publet_core/cbor/encode.rs
1//! Canonical encoder for the Section 4.1 profile.
2//!
3//! Encoding is total: every [`Value`] has exactly one representation, since
4//! the type admits no floats, no tags, and no indefinite lengths, and its
5//! maps are sorted by construction.
6
7use super::Value;
8
9/// Encode a value in canonical form.
10///
11/// The result round-trips: `decode(&encode(v))` yields `v`, and
12/// `encode(&decode(b)?)` yields `b` for any canonical `b`.
13///
14/// # Example
15///
16/// ```
17/// use std::collections::BTreeMap;
18/// use publet_core::cbor::{Value, decode, encode};
19///
20/// let map = Value::Map(BTreeMap::from([
21/// ("b".to_owned(), Value::Uint(2)),
22/// ("a".to_owned(), Value::Text("x".into())),
23/// ]));
24/// let bytes = encode(&map);
25///
26/// // Keys sorted by their UTF-8 bytes, integers in shortest form.
27/// assert_eq!(bytes, [0xa2, 0x61, b'a', 0x61, b'x', 0x61, b'b', 0x02]);
28/// // What is encoded decodes to itself.
29/// assert_eq!(decode(&bytes)?, map);
30/// # Ok::<(), publet_core::CanonError>(())
31/// ```
32#[must_use]
33pub fn encode(value: &Value) -> Vec<u8> {
34 let mut out = Vec::new();
35 write_value(&mut out, value);
36 out
37}
38
39/// Write a CBOR head with the shortest argument encoding that fits.
40///
41/// The casts below are bounded by their match arms -- each arm has already
42/// established that `arg` fits the target width -- so truncation is
43/// unreachable. `u8::try_from` would need a fallback value that could only
44/// ever mask a logic error, which is worse than an annotated cast.
45#[allow(clippy::cast_possible_truncation)]
46fn write_head(out: &mut Vec<u8>, major: u8, arg: u64) {
47 let m = major << 5;
48 match arg {
49 0..=23 => out.push(m | (arg as u8)),
50 24..=0xff => {
51 out.push(m | 0x18);
52 out.push(arg as u8);
53 }
54 0x100..=0xffff => {
55 out.push(m | 0x19);
56 out.extend_from_slice(&(arg as u16).to_be_bytes());
57 }
58 0x1_0000..=0xffff_ffff => {
59 out.push(m | 0x1a);
60 out.extend_from_slice(&(arg as u32).to_be_bytes());
61 }
62 _ => {
63 out.push(m | 0x1b);
64 out.extend_from_slice(&arg.to_be_bytes());
65 }
66 }
67}
68
69fn write_value(out: &mut Vec<u8>, value: &Value) {
70 match value {
71 Value::Uint(n) => write_head(out, 0, *n),
72 Value::Nint(n) => write_head(out, 1, *n),
73 Value::Bytes(b) => {
74 write_head(out, 2, b.len() as u64);
75 out.extend_from_slice(b);
76 }
77 Value::Text(s) => {
78 write_head(out, 3, s.len() as u64);
79 out.extend_from_slice(s.as_bytes());
80 }
81 Value::Array(items) => {
82 write_head(out, 4, items.len() as u64);
83 for item in items {
84 write_value(out, item);
85 }
86 }
87 Value::Map(entries) => {
88 write_head(out, 5, entries.len() as u64);
89 // BTreeMap iterates in Ord order, which for String is by UTF-8
90 // bytes -- exactly the ordering the profile requires.
91 for (k, v) in entries {
92 write_head(out, 3, k.len() as u64);
93 out.extend_from_slice(k.as_bytes());
94 write_value(out, v);
95 }
96 }
97 Value::Bool(false) => out.push(0xf4),
98 Value::Bool(true) => out.push(0xf5),
99 Value::Null => out.push(0xf6),
100 }
101}