Skip to main content

nibkeep_base/cbor/
convert.rs

1//! Converting between Rust types and canonical CBOR.
2
3use super::{DecodeError, Integer, Value, decode, encode};
4
5/// A Rust type that can be written as canonical CBOR.
6pub trait ToCbor {
7	/// Returns the value to encode.
8	fn to_cbor(&self) -> Value;
9}
10
11/// A Rust type that can be read from canonical CBOR.
12pub trait FromCbor: Sized {
13	/// Reads the Rust value from a decoded value.
14	///
15	/// # Errors
16	///
17	/// Returns an error if `value` does not have the shape the type expects.
18	fn from_cbor(value: &Value) -> Result<Self, Error>;
19}
20
21/// Encodes a Rust value canonically.
22#[must_use]
23pub fn to_vec<T: ToCbor + ?Sized>(value: &T) -> Vec<u8> {
24	encode(&value.to_cbor())
25}
26
27/// Decodes a Rust value from its canonical encoding.
28///
29/// # Errors
30///
31/// Returns an error if `bytes` is not a canonical encoding, or if the value it encodes
32/// does not have the shape that `T` expects.
33pub fn from_slice<T: FromCbor>(bytes: &[u8]) -> Result<T, Error> {
34	T::from_cbor(&decode(bytes)?)
35}
36
37/// Why a Rust value could not be read.
38#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
39#[non_exhaustive]
40pub enum Error {
41	/// The input is not a canonical encoding.
42	#[error(transparent)]
43	Decode(#[from] DecodeError),
44	/// The value does not have the expected shape.
45	#[error("expected {0}")]
46	Expected(&'static str),
47}
48
49/// A byte string. A plain `Vec<u8>` is an array of integers instead.
50///
51/// There is deliberately no conversion for `Option`: writing `None` as `null` would make
52/// `Some(None)` and `None` indistinguishable. Structures leave out absent fields instead.
53#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
54pub struct Bytes(pub Vec<u8>);
55
56impl ToCbor for Bytes {
57	fn to_cbor(&self) -> Value {
58		Value::Bytes(self.0.clone())
59	}
60}
61
62impl FromCbor for Bytes {
63	fn from_cbor(value: &Value) -> Result<Self, Error> {
64		match value {
65			Value::Bytes(bytes) => Ok(Self(bytes.clone())),
66			_ => Err(Error::Expected("a byte string")),
67		}
68	}
69}
70
71impl ToCbor for Value {
72	fn to_cbor(&self) -> Value {
73		self.clone()
74	}
75}
76
77impl FromCbor for Value {
78	fn from_cbor(value: &Value) -> Result<Self, Error> {
79		Ok(value.clone())
80	}
81}
82
83impl ToCbor for bool {
84	fn to_cbor(&self) -> Value {
85		Value::Bool(*self)
86	}
87}
88
89impl FromCbor for bool {
90	fn from_cbor(value: &Value) -> Result<Self, Error> {
91		match value {
92			Value::Bool(flag) => Ok(*flag),
93			_ => Err(Error::Expected("true or false")),
94		}
95	}
96}
97
98impl ToCbor for String {
99	fn to_cbor(&self) -> Value {
100		Value::Text(self.clone())
101	}
102}
103
104impl ToCbor for str {
105	fn to_cbor(&self) -> Value {
106		Value::Text(self.to_owned())
107	}
108}
109
110impl FromCbor for String {
111	fn from_cbor(value: &Value) -> Result<Self, Error> {
112		match value {
113			Value::Text(text) => Ok(text.clone()),
114			_ => Err(Error::Expected("text")),
115		}
116	}
117}
118
119impl ToCbor for Integer {
120	fn to_cbor(&self) -> Value {
121		Value::Integer(*self)
122	}
123}
124
125impl FromCbor for Integer {
126	fn from_cbor(value: &Value) -> Result<Self, Error> {
127		match value {
128			Value::Integer(integer) => Ok(*integer),
129			_ => Err(Error::Expected("an integer")),
130		}
131	}
132}
133
134macro_rules! cbor_integer {
135	($($integer:ty),*) => {
136		$(
137			impl ToCbor for $integer {
138				fn to_cbor(&self) -> Value {
139					Value::Integer(Integer::from(*self))
140				}
141			}
142
143			impl FromCbor for $integer {
144				fn from_cbor(value: &Value) -> Result<Self, Error> {
145					let integer = Integer::from_cbor(value)?;
146					<$integer>::try_from(integer).map_err(|_| {
147						Error::Expected(concat!("an integer that fits in ", stringify!($integer)))
148					})
149				}
150			}
151		)*
152	};
153}
154
155cbor_integer!(u8, u16, u32, u64, i8, i16, i32, i64);
156
157impl<T: ToCbor> ToCbor for Vec<T> {
158	fn to_cbor(&self) -> Value {
159		Value::Array(self.iter().map(ToCbor::to_cbor).collect())
160	}
161}
162
163impl<T: FromCbor> FromCbor for Vec<T> {
164	fn from_cbor(value: &Value) -> Result<Self, Error> {
165		match value {
166			Value::Array(items) => items.iter().map(T::from_cbor).collect(),
167			_ => Err(Error::Expected("an array")),
168		}
169	}
170}