Skip to main content

publet_core/cbor/
mod.rs

1//! Deterministic CBOR under the profile in Section 4.1 of the specification.
2//!
3//! The profile is narrower than [RFC 8949] canonical encoding: floating
4//! point is excluded entirely, map keys must be text, and text must be in
5//! Unicode Normalization Form C. Off-the-shelf decoders are permissive by
6//! design, which is the wrong disposition here — Section 4.1 requires that
7//! non-canonical bytes be *rejected* rather than repaired, because an
8//! object's identity is the hash of its bytes and a decoder that silently
9//! normalizes would let two encodings claim one identity.
10//!
11//! [RFC 8949]: https://www.rfc-editor.org/rfc/rfc8949
12//!
13//! # Examples
14//!
15//! ```
16//! use publet_core::cbor::{decode, encode, Value};
17//!
18//! let bytes = encode(&Value::Text("hello".into()));
19//! assert_eq!(decode(&bytes)?, Value::Text("hello".into()));
20//! # Ok::<(), publet_core::CanonError>(())
21//! ```
22//!
23//! Non-canonical input is refused, and the error names the rule:
24//!
25//! ```
26//! use publet_core::cbor::decode;
27//!
28//! // 0x18 0x05 encodes 5 in two bytes; canonical form is the single byte 0x05.
29//! let err = decode(&[0x18, 0x05]).unwrap_err();
30//! assert_eq!(err.rule(), "shortest-form integers");
31//! ```
32
33mod decode;
34mod encode;
35
36pub use decode::{DEFAULT_MAX_DEPTH, MAX_OBJECT_BYTES, decode, decode_with_limit};
37pub use encode::encode;
38
39use std::collections::BTreeMap;
40
41/// A value in the deterministic CBOR profile.
42///
43/// There is deliberately no float variant and no tag variant: the profile
44/// admits neither, so they are unrepresentable rather than rejected later.
45/// Maps are [`BTreeMap`] so that encoding is sorted by construction.
46#[derive(Debug, Clone, PartialEq, Eq)]
47#[non_exhaustive]
48pub enum Value {
49    /// A non-negative integer (CBOR major type 0).
50    Uint(u64),
51    /// A negative integer, stored as `-1 - n` (CBOR major type 1).
52    Nint(u64),
53    /// A byte string (CBOR major type 2).
54    Bytes(Vec<u8>),
55    /// A text string, valid UTF-8 in NFC (CBOR major type 3).
56    Text(String),
57    /// An array (CBOR major type 4).
58    Array(Vec<Value>),
59    /// A map with text keys, ordered by UTF-8 bytes (CBOR major type 5).
60    Map(BTreeMap<String, Value>),
61    /// `false`, `true`, or `null` (CBOR major type 7, simple values).
62    Bool(bool),
63    /// The null simple value.
64    Null,
65}
66
67impl Value {
68    /// Borrow a map entry, if this is a map containing `key`.
69    ///
70    /// # Example
71    ///
72    /// ```
73    /// use publet_core::cbor::{Value, decode};
74    ///
75    /// let value = decode(&[0xa1, 0x61, b'a', 0x01])?; // {"a": 1}
76    /// assert_eq!(value.get("a"), Some(&Value::Uint(1)));
77    /// assert_eq!(value.get("b"), None);
78    /// // Not a map, so there is nothing to get.
79    /// assert_eq!(Value::Uint(1).get("a"), None);
80    /// # Ok::<(), publet_core::CanonError>(())
81    /// ```
82    #[must_use]
83    pub fn get(&self, key: &str) -> Option<&Value> {
84        match self {
85            Self::Map(m) => m.get(key),
86            _ => None,
87        }
88    }
89
90    /// Borrow the text, if this is a text string.
91    ///
92    /// # Example
93    ///
94    /// ```
95    /// use publet_core::cbor::Value;
96    ///
97    /// assert_eq!(Value::Text("hello".into()).as_text(), Some("hello"));
98    /// assert_eq!(Value::Uint(1).as_text(), None);
99    /// ```
100    #[must_use]
101    pub fn as_text(&self) -> Option<&str> {
102        match self {
103            Self::Text(s) => Some(s),
104            _ => None,
105        }
106    }
107
108    /// Borrow the bytes, if this is a byte string.
109    ///
110    /// # Example
111    ///
112    /// ```
113    /// use publet_core::cbor::Value;
114    ///
115    /// assert_eq!(Value::Bytes(vec![1, 2]).as_bytes(), Some(&[1u8, 2][..]));
116    /// assert_eq!(Value::Text("hello".into()).as_bytes(), None);
117    /// ```
118    #[must_use]
119    pub fn as_bytes(&self) -> Option<&[u8]> {
120        match self {
121            Self::Bytes(b) => Some(b),
122            _ => None,
123        }
124    }
125
126    /// The value, if this is a non-negative integer.
127    ///
128    /// # Example
129    ///
130    /// ```
131    /// use publet_core::cbor::Value;
132    ///
133    /// assert_eq!(Value::Uint(7).as_uint(), Some(7));
134    /// // -1 is a negative integer, not a non-negative one.
135    /// assert_eq!(Value::Nint(0).as_uint(), None);
136    /// ```
137    #[must_use]
138    pub fn as_uint(&self) -> Option<u64> {
139        match self {
140            Self::Uint(n) => Some(*n),
141            _ => None,
142        }
143    }
144}