Skip to main content

nibkeep_base/cbor/
value.rs

1//! The values that canonical CBOR can encode.
2
3use std::cmp::Ordering;
4use std::collections::{BTreeMap, btree_map};
5
6use super::{initial_byte, length, major};
7
8/// An integer in the range CBOR represents directly: −2^64 to 2^64 − 1.
9#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub struct Integer(i128);
11
12impl Integer {
13	/// The smallest integer, −2^64.
14	pub const MIN: Self = Self(-(1 << 64));
15	/// The largest integer, 2^64 − 1.
16	pub const MAX: Self = Self((1 << 64) - 1);
17
18	/// Returns the integer, or `None` if `value` is outside the range CBOR represents.
19	#[must_use]
20	pub const fn new(value: i128) -> Option<Self> {
21		if value >= Self::MIN.0 && value <= Self::MAX.0 {
22			Some(Self(value))
23		} else {
24			None
25		}
26	}
27
28	/// Returns the value.
29	#[must_use]
30	pub const fn get(self) -> i128 {
31		self.0
32	}
33
34	/// The major type and argument of the integer's header: major type 0 with the value
35	/// itself, or major type 1 with −1 − value.
36	pub(super) fn header(self) -> (u8, u64) {
37		if self.0 >= 0 {
38			(
39				major::UNSIGNED,
40				u64::try_from(self.0).expect("at most 2^64 - 1"),
41			)
42		} else {
43			(
44				major::NEGATIVE,
45				u64::try_from(-1 - self.0).expect("at least -2^64"),
46			)
47		}
48	}
49}
50
51macro_rules! integer_from {
52	($($from:ty),*) => {
53		$(
54			impl From<$from> for Integer {
55				fn from(value: $from) -> Self {
56					Self(i128::from(value))
57				}
58			}
59		)*
60	};
61}
62
63integer_from!(u8, u16, u32, u64, i8, i16, i32, i64);
64
65/// The error returned when an [`Integer`] does not fit the requested type.
66#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
67#[error("integer out of range")]
68pub struct IntegerOutOfRange;
69
70macro_rules! integer_into {
71	($($into:ty),*) => {
72		$(
73			impl TryFrom<Integer> for $into {
74				type Error = IntegerOutOfRange;
75
76				fn try_from(value: Integer) -> Result<Self, Self::Error> {
77					<$into>::try_from(value.0).map_err(|_| IntegerOutOfRange)
78				}
79			}
80		)*
81	};
82}
83
84integer_into!(u8, u16, u32, u64, i8, i16, i32, i64, usize);
85
86/// A value that canonical CBOR can encode.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub enum Value {
89	/// An integer: major types 0 and 1.
90	Integer(Integer),
91	/// A byte string: major type 2.
92	Bytes(Vec<u8>),
93	/// A text string: major type 3.
94	Text(String),
95	/// An array: major type 4.
96	Array(Vec<Value>),
97	/// A map with integer or text keys: major type 5.
98	Map(Map),
99	/// A UUID: tag 37 with a 16-byte byte string.
100	Uuid([u8; 16]),
101	/// A decimal fraction, `mantissa × 10^exponent`: tag 4 with an array of the two
102	/// integers. The precision is part of the value, so 1.5 and 1.50 are different values.
103	Decimal {
104		/// The power of ten.
105		exponent: Integer,
106		/// The digits.
107		mantissa: Integer,
108	},
109	/// `true` or `false`.
110	Bool(bool),
111	/// `null`.
112	Null,
113}
114
115impl From<Integer> for Value {
116	fn from(value: Integer) -> Self {
117		Self::Integer(value)
118	}
119}
120
121impl From<String> for Value {
122	fn from(value: String) -> Self {
123		Self::Text(value)
124	}
125}
126
127impl From<&str> for Value {
128	fn from(value: &str) -> Self {
129		Self::Text(value.to_owned())
130	}
131}
132
133impl From<bool> for Value {
134	fn from(value: bool) -> Self {
135		Self::Bool(value)
136	}
137}
138
139impl From<Map> for Value {
140	fn from(value: Map) -> Self {
141		Self::Map(value)
142	}
143}
144
145impl From<Vec<Value>> for Value {
146	fn from(value: Vec<Value>) -> Self {
147		Self::Array(value)
148	}
149}
150
151/// The key of a map entry: an integer or a text string.
152#[derive(Clone, Debug, PartialEq, Eq, Hash)]
153pub enum MapKey {
154	/// An integer key.
155	Integer(Integer),
156	/// A text key.
157	Text(String),
158}
159
160impl MapKey {
161	/// The parts of the key's encoding, in the order that decides the canonical order of
162	/// keys: the first byte, the argument of the header and the payload. Comparing these
163	/// gives the same result as comparing the encodings byte by byte, because two
164	/// encodings with the same first byte write their arguments with the same width.
165	fn order(&self) -> (u8, u64, &[u8]) {
166		match self {
167			Self::Integer(integer) => {
168				let (major, argument) = integer.header();
169				(initial_byte(major, argument), argument, &[])
170			}
171			Self::Text(text) => {
172				let argument = length(text.len());
173				(
174					initial_byte(major::TEXT, argument),
175					argument,
176					text.as_bytes(),
177				)
178			}
179		}
180	}
181}
182
183impl Ord for MapKey {
184	/// The canonical order: the bytewise order of the keys' encodings.
185	fn cmp(&self, other: &Self) -> Ordering {
186		self.order().cmp(&other.order())
187	}
188}
189
190impl PartialOrd for MapKey {
191	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
192		Some(self.cmp(other))
193	}
194}
195
196impl From<Integer> for MapKey {
197	fn from(value: Integer) -> Self {
198		Self::Integer(value)
199	}
200}
201
202impl From<i64> for MapKey {
203	fn from(value: i64) -> Self {
204		Self::Integer(Integer::from(value))
205	}
206}
207
208impl From<u64> for MapKey {
209	fn from(value: u64) -> Self {
210		Self::Integer(Integer::from(value))
211	}
212}
213
214impl From<i32> for MapKey {
215	fn from(value: i32) -> Self {
216		Self::Integer(Integer::from(value))
217	}
218}
219
220impl From<String> for MapKey {
221	fn from(value: String) -> Self {
222		Self::Text(value)
223	}
224}
225
226impl From<&str> for MapKey {
227	fn from(value: &str) -> Self {
228		Self::Text(value.to_owned())
229	}
230}
231
232/// A map whose entries are kept in canonical order.
233#[derive(Clone, Debug, Default, PartialEq, Eq)]
234pub struct Map(BTreeMap<MapKey, Value>);
235
236impl Map {
237	/// Returns an empty map.
238	#[must_use]
239	pub fn new() -> Self {
240		Self::default()
241	}
242
243	/// Inserts an entry and returns the value it replaced, if any.
244	pub fn insert(&mut self, key: impl Into<MapKey>, value: impl Into<Value>) -> Option<Value> {
245		self.0.insert(key.into(), value.into())
246	}
247
248	/// Returns the value for `key`.
249	#[must_use]
250	pub fn get(&self, key: &MapKey) -> Option<&Value> {
251		self.0.get(key)
252	}
253
254	/// Removes the entry for `key` and returns its value.
255	pub fn remove(&mut self, key: &MapKey) -> Option<Value> {
256		self.0.remove(key)
257	}
258
259	/// The number of entries.
260	#[must_use]
261	pub fn len(&self) -> usize {
262		self.0.len()
263	}
264
265	/// Whether the map has no entries.
266	#[must_use]
267	pub fn is_empty(&self) -> bool {
268		self.0.is_empty()
269	}
270
271	/// The entries in canonical order.
272	pub fn iter(&self) -> btree_map::Iter<'_, MapKey, Value> {
273		self.0.iter()
274	}
275
276	/// Builds a map from entries whose keys are already unique and in canonical order.
277	pub(super) fn from_sorted(entries: Vec<(MapKey, Value)>) -> Self {
278		debug_assert!(entries.windows(2).all(|pair| pair[0].0 < pair[1].0));
279		Self(entries.into_iter().collect())
280	}
281}
282
283impl FromIterator<(MapKey, Value)> for Map {
284	fn from_iter<I: IntoIterator<Item = (MapKey, Value)>>(entries: I) -> Self {
285		Self(entries.into_iter().collect())
286	}
287}
288
289impl IntoIterator for Map {
290	type Item = (MapKey, Value);
291	type IntoIter = btree_map::IntoIter<MapKey, Value>;
292
293	fn into_iter(self) -> Self::IntoIter {
294		self.0.into_iter()
295	}
296}
297
298impl<'a> IntoIterator for &'a Map {
299	type Item = (&'a MapKey, &'a Value);
300	type IntoIter = btree_map::Iter<'a, MapKey, Value>;
301
302	fn into_iter(self) -> Self::IntoIter {
303		self.0.iter()
304	}
305}