Skip to main content

nibkeep_base/cbor/
decode.rs

1//! Reading values, accepting only their canonical encoding.
2
3use std::cmp::Ordering;
4use std::fmt;
5
6use super::{Integer, Map, MapKey, TAG_DECIMAL, TAG_UUID, Value, major, simple};
7
8/// The deepest nesting of arrays and maps that [`decode`] accepts.
9pub const MAX_DEPTH: usize = 64;
10
11/// Decodes a value from its canonical encoding.
12///
13/// # Errors
14///
15/// Returns an error if `bytes` is not exactly the canonical encoding of one value: for
16/// example if a number is not in its shortest form, map keys are out of order, the input
17/// ends early or continues after the value, or it uses a part of CBOR that canonical CBOR
18/// leaves out, such as floating-point numbers.
19pub fn decode(bytes: &[u8]) -> Result<Value, DecodeError> {
20	let mut decoder = Decoder { bytes, position: 0 };
21	let value = decoder.value(0)?;
22	if decoder.position == bytes.len() {
23		Ok(value)
24	} else {
25		Err(DecodeError::new(
26			decoder.position,
27			DecodeErrorKind::TrailingBytes,
28		))
29	}
30}
31
32/// Decodes the first value of a sequence of values ([RFC 8742]), each in its canonical
33/// encoding, and returns it with the length of its encoding, where the next value starts.
34///
35/// [RFC 8742]: https://www.rfc-editor.org/rfc/rfc8742
36///
37/// # Errors
38///
39/// Returns an error if `bytes` does not start with the canonical encoding of a value.
40pub fn decode_first(bytes: &[u8]) -> Result<(Value, usize), DecodeError> {
41	let mut decoder = Decoder { bytes, position: 0 };
42	let value = decoder.value(0)?;
43	Ok((value, decoder.position))
44}
45
46/// Why input was rejected, and where.
47#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
48#[error("{kind} at byte {offset}")]
49pub struct DecodeError {
50	offset: usize,
51	kind: DecodeErrorKind,
52}
53
54impl DecodeError {
55	fn new(offset: usize, kind: DecodeErrorKind) -> Self {
56		Self { offset, kind }
57	}
58
59	/// The position in the input of the data item that was rejected.
60	#[must_use]
61	pub fn offset(&self) -> usize {
62		self.offset
63	}
64
65	/// Why the input was rejected.
66	#[must_use]
67	pub fn kind(&self) -> &DecodeErrorKind {
68		&self.kind
69	}
70}
71
72/// The reasons why input is rejected.
73#[derive(Clone, Debug, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum DecodeErrorKind {
76	/// The input ends in the middle of a data item, or a length is longer than the rest of
77	/// the input.
78	UnexpectedEnd,
79	/// There are bytes after the end of the value.
80	TrailingBytes,
81	/// A number, length or tag is not in its shortest form.
82	NotShortest,
83	/// A byte string, text string, array or map has an indefinite length.
84	IndefiniteLength,
85	/// A header uses reserved additional information (28 to 30).
86	Reserved,
87	/// A floating-point number.
88	Float,
89	/// A simple value other than `false`, `true` and `null`.
90	SimpleValue,
91	/// A text string is not valid UTF-8.
92	InvalidUtf8,
93	/// A map key is neither an integer nor a text string.
94	InvalidMapKey,
95	/// A map key is not greater than the key before it.
96	UnsortedKeys,
97	/// A map key appears twice.
98	DuplicateKey,
99	/// A tag other than the decimal fraction (4) and the UUID (37).
100	UnsupportedTag,
101	/// A tag's content does not have the shape the tag requires.
102	InvalidTagContent,
103	/// Arrays and maps are nested more than [`MAX_DEPTH`] levels deep.
104	TooDeep,
105}
106
107impl fmt::Display for DecodeErrorKind {
108	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109		f.write_str(match self {
110			Self::UnexpectedEnd => "unexpected end of input",
111			Self::TrailingBytes => "bytes after the end of the value",
112			Self::NotShortest => "number not in its shortest form",
113			Self::IndefiniteLength => "indefinite length",
114			Self::Reserved => "reserved additional information",
115			Self::Float => "floating-point number",
116			Self::SimpleValue => "simple value other than false, true and null",
117			Self::InvalidUtf8 => "text that is not valid UTF-8",
118			Self::InvalidMapKey => "map key that is neither an integer nor text",
119			Self::UnsortedKeys => "map key out of order",
120			Self::DuplicateKey => "duplicate map key",
121			Self::UnsupportedTag => "unsupported tag",
122			Self::InvalidTagContent => "invalid tag content",
123			Self::TooDeep => "nesting too deep",
124		})
125	}
126}
127
128struct Decoder<'a> {
129	bytes: &'a [u8],
130	position: usize,
131}
132
133impl<'a> Decoder<'a> {
134	/// Reads the data item at the current position. `depth` is the number of arrays and
135	/// maps around it.
136	fn value(&mut self, depth: usize) -> Result<Value, DecodeError> {
137		let start = self.position;
138		let initial = self.byte()?;
139		let (major, info) = (initial >> 5, initial & 0x1f);
140		match major {
141			major::UNSIGNED => {
142				let argument = self.argument(info, start)?;
143				Ok(Value::Integer(Integer::from(argument)))
144			}
145			major::NEGATIVE => {
146				let argument = self.argument(info, start)?;
147				let value = Integer::new(-1 - i128::from(argument)).expect("at least -2^64");
148				Ok(Value::Integer(value))
149			}
150			major::BYTES => {
151				let argument = self.argument(info, start)?;
152				Ok(Value::Bytes(self.take(argument, start)?.to_vec()))
153			}
154			major::TEXT => {
155				let argument = self.argument(info, start)?;
156				let bytes = self.take(argument, start)?;
157				let text = std::str::from_utf8(bytes)
158					.map_err(|_| DecodeError::new(start, DecodeErrorKind::InvalidUtf8))?;
159				Ok(Value::Text(text.to_owned()))
160			}
161			major::ARRAY => {
162				let argument = self.argument(info, start)?;
163				Self::enter(depth, start)?;
164				let count = self.count(argument, start)?;
165				let mut items = Vec::with_capacity(count);
166				for _ in 0..count {
167					items.push(self.value(depth + 1)?);
168				}
169				Ok(Value::Array(items))
170			}
171			major::MAP => {
172				let argument = self.argument(info, start)?;
173				Self::enter(depth, start)?;
174				let count = self.count(argument, start)?;
175				self.map(count, depth)
176			}
177			major::TAG => {
178				let argument = self.argument(info, start)?;
179				self.tag(argument, start)
180			}
181			_ => Self::simple(initial, start),
182		}
183	}
184
185	fn map(&mut self, count: usize, depth: usize) -> Result<Value, DecodeError> {
186		let mut entries: Vec<(MapKey, Value)> = Vec::with_capacity(count);
187		for _ in 0..count {
188			let key_start = self.position;
189			let key = self.map_key()?;
190			if let Some((previous, _)) = entries.last() {
191				match previous.cmp(&key) {
192					Ordering::Less => {}
193					Ordering::Equal => {
194						return Err(DecodeError::new(key_start, DecodeErrorKind::DuplicateKey));
195					}
196					Ordering::Greater => {
197						return Err(DecodeError::new(key_start, DecodeErrorKind::UnsortedKeys));
198					}
199				}
200			}
201			let value = self.value(depth + 1)?;
202			entries.push((key, value));
203		}
204		Ok(Value::Map(Map::from_sorted(entries)))
205	}
206
207	/// Reads a map key, which must be an integer or a text string. Anything else is
208	/// rejected before it is read, so a key can never start a nested structure.
209	fn map_key(&mut self) -> Result<MapKey, DecodeError> {
210		let start = self.position;
211		let major = self.peek()? >> 5;
212		if !matches!(major, major::UNSIGNED | major::NEGATIVE | major::TEXT) {
213			return Err(DecodeError::new(start, DecodeErrorKind::InvalidMapKey));
214		}
215		match self.value(0)? {
216			Value::Integer(integer) => Ok(MapKey::Integer(integer)),
217			Value::Text(text) => Ok(MapKey::Text(text)),
218			_ => unreachable!("major types 0, 1 and 3 decode to integers or text"),
219		}
220	}
221
222	/// Reads the content of the tag whose header started at `start`. The content of each
223	/// allowed tag has a fixed shape, so it is read directly rather than as a nested value:
224	/// tags never nest, and they do not count towards [`MAX_DEPTH`].
225	fn tag(&mut self, number: u64, start: usize) -> Result<Value, DecodeError> {
226		match number {
227			TAG_DECIMAL => {
228				let content = self.position;
229				let invalid = || DecodeError::new(content, DecodeErrorKind::InvalidTagContent);
230				let (major, count) = self.header()?;
231				if major != major::ARRAY || count != 2 {
232					return Err(invalid());
233				}
234				let exponent = self.integer().ok_or_else(invalid)??;
235				let mantissa = self.integer().ok_or_else(invalid)??;
236				Ok(Value::Decimal { exponent, mantissa })
237			}
238			TAG_UUID => {
239				let content = self.position;
240				let invalid = || DecodeError::new(content, DecodeErrorKind::InvalidTagContent);
241				let (major, len) = self.header()?;
242				if major != major::BYTES || len != 16 {
243					return Err(invalid());
244				}
245				let bytes = self.take(len, content)?;
246				Ok(Value::Uuid(bytes.try_into().expect("took 16 bytes")))
247			}
248			_ => Err(DecodeError::new(start, DecodeErrorKind::UnsupportedTag)),
249		}
250	}
251
252	/// Reads an integer, or returns `None` without consuming anything if the next data
253	/// item is not an integer.
254	fn integer(&mut self) -> Option<Result<Integer, DecodeError>> {
255		let major = match self.peek() {
256			Ok(initial) => initial >> 5,
257			Err(error) => return Some(Err(error)),
258		};
259		if !matches!(major, major::UNSIGNED | major::NEGATIVE) {
260			return None;
261		}
262		Some(self.value(0).map(|value| match value {
263			Value::Integer(integer) => integer,
264			_ => unreachable!("major types 0 and 1 decode to integers"),
265		}))
266	}
267
268	/// Reads a header of major types 0 to 6 and returns its major type and argument.
269	fn header(&mut self) -> Result<(u8, u64), DecodeError> {
270		let start = self.position;
271		let initial = self.byte()?;
272		let (major, info) = (initial >> 5, initial & 0x1f);
273		if major > major::TAG {
274			return Ok((major, 0));
275		}
276		Ok((major, self.argument(info, start)?))
277	}
278
279	fn simple(initial: u8, start: usize) -> Result<Value, DecodeError> {
280		match initial {
281			simple::FALSE => Ok(Value::Bool(false)),
282			simple::TRUE => Ok(Value::Bool(true)),
283			simple::NULL => Ok(Value::Null),
284			0xf9..=0xfb => Err(DecodeError::new(start, DecodeErrorKind::Float)),
285			0xfc..=0xfe => Err(DecodeError::new(start, DecodeErrorKind::Reserved)),
286			_ => Err(DecodeError::new(start, DecodeErrorKind::SimpleValue)),
287		}
288	}
289
290	/// Fails if an array or map at `depth` would be nested too deeply.
291	fn enter(depth: usize, start: usize) -> Result<(), DecodeError> {
292		if depth < MAX_DEPTH {
293			Ok(())
294		} else {
295			Err(DecodeError::new(start, DecodeErrorKind::TooDeep))
296		}
297	}
298
299	/// Reads the argument of a header whose first byte had the additional information
300	/// `info`, and checks that it is in its shortest form.
301	fn argument(&mut self, info: u8, start: usize) -> Result<u64, DecodeError> {
302		let not_shortest = || DecodeError::new(start, DecodeErrorKind::NotShortest);
303		match info {
304			0..=23 => Ok(u64::from(info)),
305			24 => {
306				let argument = u64::from(self.byte()?);
307				if argument < 24 {
308					Err(not_shortest())
309				} else {
310					Ok(argument)
311				}
312			}
313			25 => {
314				let argument = u64::from(u16::from_be_bytes(self.array()?));
315				if argument <= 0xff {
316					Err(not_shortest())
317				} else {
318					Ok(argument)
319				}
320			}
321			26 => {
322				let argument = u64::from(u32::from_be_bytes(self.array()?));
323				if argument <= 0xffff {
324					Err(not_shortest())
325				} else {
326					Ok(argument)
327				}
328			}
329			27 => {
330				let argument = u64::from_be_bytes(self.array()?);
331				if argument <= 0xffff_ffff {
332					Err(not_shortest())
333				} else {
334					Ok(argument)
335				}
336			}
337			28..=30 => Err(DecodeError::new(start, DecodeErrorKind::Reserved)),
338			_ => Err(DecodeError::new(start, DecodeErrorKind::IndefiniteLength)),
339		}
340	}
341
342	/// Checks that `count` items can follow: each takes at least one byte, so a count
343	/// larger than the rest of the input cannot be right. This also keeps the decoder from
344	/// reserving memory for a count that the input could never fill.
345	fn count(&self, count: u64, start: usize) -> Result<usize, DecodeError> {
346		usize::try_from(count)
347			.ok()
348			.filter(|&count| count <= self.remaining())
349			.ok_or_else(|| DecodeError::new(start, DecodeErrorKind::UnexpectedEnd))
350	}
351
352	/// Takes the next `len` bytes.
353	fn take(&mut self, len: u64, start: usize) -> Result<&'a [u8], DecodeError> {
354		let len = self.count(len, start)?;
355		let bytes = &self.bytes[self.position..self.position + len];
356		self.position += len;
357		Ok(bytes)
358	}
359
360	fn peek(&self) -> Result<u8, DecodeError> {
361		self.bytes
362			.get(self.position)
363			.copied()
364			.ok_or_else(|| DecodeError::new(self.position, DecodeErrorKind::UnexpectedEnd))
365	}
366
367	fn byte(&mut self) -> Result<u8, DecodeError> {
368		let byte = *self
369			.bytes
370			.get(self.position)
371			.ok_or_else(|| DecodeError::new(self.position, DecodeErrorKind::UnexpectedEnd))?;
372		self.position += 1;
373		Ok(byte)
374	}
375
376	fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
377		let start = self.position;
378		let bytes = self.take(N as u64, start)?;
379		Ok(bytes.try_into().expect("took exactly N bytes"))
380	}
381
382	fn remaining(&self) -> usize {
383		self.bytes.len() - self.position
384	}
385}