const_cbor/decode.rs
1//! CBOR decoding from borrowed input.
2//!
3//! [`Decoder`] walks a `&[u8]` input and exposes one method per CBOR type.
4//! Text strings and byte strings are returned as borrows of the input —
5//! no copying, no allocation. All methods return typed results; malformed
6//! input never panics.
7
8use crate::error::Error;
9use crate::head::{Major, Simple, read_head};
10
11/// Maximum container nesting tolerated by [`Decoder::skip`].
12pub const SKIP_LIMIT: usize = 32;
13
14/// Deserializes CBOR items from a fixed input slice.
15#[derive(Clone, Copy, Debug)]
16pub struct Decoder<'a> {
17 pub(crate) input: &'a [u8],
18 pub(crate) pos: usize,
19}
20
21impl<'a> Decoder<'a> {
22 /// Creates a decoder reading from the start of `input`.
23 #[inline]
24 #[must_use]
25 pub const fn new(input: &'a [u8]) -> Self {
26 Self { input, pos: 0 }
27 }
28
29 /// Number of bytes consumed so far.
30 #[inline]
31 #[must_use]
32 pub const fn position(&self) -> usize {
33 self.pos
34 }
35
36 /// Bytes left unread.
37 #[inline]
38 #[must_use]
39 pub const fn remaining(&self) -> usize {
40 self.input.len() - self.pos
41 }
42
43 /// `true` when every input byte has been consumed.
44 #[inline]
45 #[must_use]
46 pub const fn is_empty(&self) -> bool {
47 self.remaining() == 0
48 }
49
50 /// Major type of the next item without consuming it.
51 #[inline]
52 #[must_use]
53 pub fn peek_major(&self) -> Option<Major> {
54 self.input.get(self.pos).map(|&b| Major::from_initial(b))
55 }
56
57 /// Reads and consumes the next head.
58 #[inline]
59 fn next_head(&mut self) -> Result<(Major, u64), Error> {
60 let (major, arg, used) = read_head(&self.input[self.pos..])?;
61 self.pos += used;
62 Ok((major, arg))
63 }
64
65 /// Reads the next head, allowing indefinite lengths (used by the
66 /// `indefinite` and `diagnostic` features).
67 #[cfg(any(feature = "indefinite", feature = "diagnostic"))]
68 #[inline]
69 pub(crate) fn next_head_ext(&mut self) -> Result<(Major, u64, bool), Error> {
70 let (major, arg, used, indef) = crate::head::read_head_ext(&self.input[self.pos..])?;
71 self.pos += used;
72 Ok((major, arg, indef))
73 }
74
75 /// Requires the next item to be major type `want`, returning its argument.
76 #[inline]
77 fn expect_head(&mut self, want: Major) -> Result<u64, Error> {
78 let (major, arg) = self.next_head()?;
79 match major == want {
80 true => Ok(arg),
81 false => Err(Error::TYPE_MISMATCH),
82 }
83 }
84
85 /// Converts an argument into a `usize` content length within input bounds.
86 #[inline]
87 pub(crate) fn content_len(&self, arg: u64) -> Result<usize, Error> {
88 let len = usize::try_from(arg).map_err(|_| Error::TRUNCATED)?;
89 match len <= self.remaining() {
90 true => Ok(len),
91 false => Err(Error::TRUNCATED),
92 }
93 }
94
95 /// Decodes an unsigned integer, failing if it exceeds `T::MAX`.
96 #[inline]
97 fn uint_as<T: TryFrom<u64>>(&mut self) -> Result<T, Error> {
98 let v = self.expect_head(Major::Unsigned)?;
99 T::try_from(v).map_err(|_| Error::INTEGER_OUT_OF_RANGE)
100 }
101
102 /// Decodes a signed integer (`-1 - n` mapping), range-checked.
103 #[inline]
104 fn int_as<T: TryFrom<i64>>(&mut self) -> Result<T, Error> {
105 match self.peek_major() {
106 Some(Major::Unsigned) => {
107 let v = self.uint_as::<i64>()?;
108 T::try_from(v).map_err(|_| Error::INTEGER_OUT_OF_RANGE)
109 }
110 _ => {
111 let n = self.expect_head(Major::Negative)?;
112 // `-1 - n >= i64::MIN` requires n <= i64::MAX.
113 match i64::try_from(n).is_ok() {
114 true => T::try_from(-1 - n as i64).map_err(|_| Error::INTEGER_OUT_OF_RANGE),
115 false => Err(Error::INTEGER_OUT_OF_RANGE),
116 }
117 }
118 }
119 }
120
121 /// Decodes an unsigned integer that fits in `u8`.
122 ///
123 /// # Errors
124 ///
125 /// [`Error::TYPE_MISMATCH`] for non-integers; [`Error::INTEGER_OUT_OF_RANGE`]
126 /// when the value exceeds `u8::MAX`.
127 #[inline]
128 pub fn u8(&mut self) -> Result<u8, Error> {
129 self.uint_as()
130 }
131
132 /// Decodes an unsigned integer that fits in `u16`.
133 ///
134 /// # Errors
135 ///
136 /// As [`Decoder::u8`], with the wider target range.
137 #[inline]
138 pub fn u16(&mut self) -> Result<u16, Error> {
139 self.uint_as()
140 }
141
142 /// Decodes an unsigned integer that fits in `u32`.
143 ///
144 /// # Errors
145 ///
146 /// As [`Decoder::u8`], with the wider target range.
147 #[inline]
148 pub fn u32(&mut self) -> Result<u32, Error> {
149 self.uint_as()
150 }
151
152 /// Decodes any CBOR unsigned integer into `u64`.
153 ///
154 /// # Errors
155 ///
156 /// Returns [`Error::TYPE_MISMATCH`] for other major types.
157 #[inline]
158 pub fn u64(&mut self) -> Result<u64, Error> {
159 self.expect_head(Major::Unsigned)
160 }
161
162 /// Decodes a negative or non-negative integer into `i8`.
163 ///
164 /// # Errors
165 ///
166 /// [`Error::TYPE_MISMATCH`] for non-integers;
167 /// [`Error::INTEGER_OUT_OF_RANGE`] outside the `i8` range.
168 #[inline]
169 pub fn i8(&mut self) -> Result<i8, Error> {
170 self.int_as()
171 }
172
173 /// Decodes a signed integer into `i16`.
174 ///
175 /// # Errors
176 ///
177 /// As [`Decoder::i8`], with the wider target range.
178 #[inline]
179 pub fn i16(&mut self) -> Result<i16, Error> {
180 self.int_as()
181 }
182
183 /// Decodes a signed integer into `i32`.
184 ///
185 /// # Errors
186 ///
187 /// As [`Decoder::i8`], with the wider target range.
188 #[inline]
189 pub fn i32(&mut self) -> Result<i32, Error> {
190 self.int_as()
191 }
192
193 /// Decodes any CBOR integer (major types 0 and 1) into `i64`.
194 ///
195 /// # Errors
196 ///
197 /// [`Error::TYPE_MISMATCH`] for non-integers;
198 /// [`Error::INTEGER_OUT_OF_RANGE`] below `i64::MIN`.
199 #[inline]
200 pub fn i64(&mut self) -> Result<i64, Error> {
201 self.int_as()
202 }
203
204 /// Borrows a byte string's contents from the input.
205 ///
206 /// # Errors
207 ///
208 /// [`Error::TYPE_MISMATCH`] if not a byte string; [`Error::TRUNCATED`]
209 /// if the declared length exceeds the input.
210 #[inline]
211 pub fn bytes(&mut self) -> Result<&'a [u8], Error> {
212 self.bytes_of(Major::Bytes)
213 }
214
215 /// Borrows a text string from the input after validating UTF-8.
216 ///
217 /// # Errors
218 ///
219 /// [`Error::TYPE_MISMATCH`] if not a text string; [`Error::INVALID_UTF8`]
220 /// if the payload violates RFC 3629; [`Error::TRUNCATED`] on short input.
221 #[inline]
222 pub fn str(&mut self) -> Result<&'a str, Error> {
223 let raw = self.bytes_of(Major::Text)?;
224 core::str::from_utf8(raw).map_err(|_| Error::INVALID_UTF8)
225 }
226
227 #[inline]
228 pub(crate) fn bytes_of(&mut self, major: Major) -> Result<&'a [u8], Error> {
229 let arg = self.expect_head(major)?;
230 let len = self.content_len(arg)?;
231 let start = self.pos;
232 self.pos += len;
233 Ok(&self.input[start..start + len])
234 }
235
236 /// Decodes `true` or `false`.
237 ///
238 /// # Errors
239 ///
240 /// Returns [`Error::TYPE_MISMATCH`] for any other item.
241 #[inline]
242 pub fn bool(&mut self) -> Result<bool, Error> {
243 let s = self.simple_value()?;
244 match s.0 {
245 20 => Ok(false),
246 21 => Ok(true),
247 _ => Err(Error::TYPE_MISMATCH),
248 }
249 }
250
251 /// Decodes `null`; returns whether the value was null without consuming
252 /// anything else. Use [`Decoder::peek_major`] for generic lookahead.
253 ///
254 /// # Errors
255 ///
256 /// Propagates decode errors from malformed heads only.
257 #[inline]
258 pub fn is_null(&mut self) -> Result<bool, Error> {
259 match self.peek_simple() {
260 Some(s) if s.0 == Simple::NULL.0 => {
261 self.next_head()?;
262 Ok(true)
263 }
264 _ => Ok(false),
265 }
266 }
267
268 /// Decodes `undefined`.
269 ///
270 /// # Errors
271 ///
272 /// Returns [`Error::TYPE_MISMATCH`] for any other item.
273 #[inline]
274 pub fn undefined(&mut self) -> Result<(), Error> {
275 let s = self.simple_value()?;
276 match s.0 == Simple::UNDEFINED.0 {
277 true => Ok(()),
278 false => Err(Error::TYPE_MISMATCH),
279 }
280 }
281
282 /// Decodes any simple value (including booleans and null).
283 ///
284 /// # Errors
285 ///
286 /// [`Error::TYPE_MISMATCH`] for floats and non-major-7 items;
287 /// [`Error::INVALID_SIMPLE`] for two-byte encodings of values below 32.
288 #[inline]
289 pub fn simple(&mut self) -> Result<Simple, Error> {
290 self.simple_value()
291 }
292
293 #[inline]
294 fn peek_simple(&self) -> Option<Simple> {
295 match self.input.get(self.pos) {
296 Some(&b) if b >> 5 == 7 && b & 0x1f < 24 => Some(Simple(b & 0x1f)),
297 _ => None,
298 }
299 }
300
301 #[inline]
302 fn simple_value(&mut self) -> Result<Simple, Error> {
303 // Distinguish one-byte from two-byte form: values below 32 are
304 // forbidden in the two-byte encoding (RFC 8949 §3.3).
305 let two_byte = matches!(
306 self.input.get(self.pos),
307 Some(b) if b >> 5 == 7 && (b & 0x1f) == 24
308 );
309 let (major, arg) = self.next_head()?;
310 if major != Major::Simple {
311 return Err(Error::TYPE_MISMATCH);
312 }
313 match (arg, two_byte) {
314 (0..=23, false) | (32..=255, true) => Ok(Simple(arg as u8)),
315 (_, true) => Err(Error::INVALID_SIMPLE),
316 // ai 25–27 carry floating-point payloads, not simple values.
317 _ => Err(Error::FLOAT_UNSUPPORTED),
318 }
319 }
320
321 /// Reads a tag number; the tagged item follows immediately.
322 ///
323 /// Tag semantics are application concerns (RFC 8949 §3.4); this returns
324 /// only the number.
325 ///
326 /// # Errors
327 ///
328 /// Returns [`Error::TYPE_MISMATCH`] if the item is not a tag.
329 #[inline]
330 pub fn tag(&mut self) -> Result<u64, Error> {
331 self.expect_head(Major::Tag)
332 }
333
334 /// Reads an array header, returning the number of following items.
335 ///
336 /// # Errors
337 ///
338 /// Returns [`Error::TYPE_MISMATCH`] if the item is not an array.
339 #[inline]
340 pub fn array_len(&mut self) -> Result<usize, Error> {
341 let n = self.expect_head(Major::Array)?;
342 usize::try_from(n).map_err(|_| Error::INTEGER_OUT_OF_RANGE)
343 }
344
345 /// Reads a map header, returning the number of following key/value pairs.
346 ///
347 /// # Errors
348 ///
349 /// Returns [`Error::TYPE_MISMATCH`] if the item is not a map.
350 #[inline]
351 pub fn map_len(&mut self) -> Result<usize, Error> {
352 let n = self.expect_head(Major::Map)?;
353 usize::try_from(n).map_err(|_| Error::INTEGER_OUT_OF_RANGE)
354 }
355
356 /// Consumes exactly one complete data item, whatever its type.
357 ///
358 /// Nested containers are traversed iteratively up to [`SKIP_LIMIT`]
359 /// levels deep; deeper input yields [`Error::DEPTH_EXCEEDED`].
360 ///
361 /// # Errors
362 ///
363 /// Any structural error ([`Error::TRUNCATED`],
364 /// [`Error::INVALID_ADDITIONAL_INFO`], [`Error::INVALID_SIMPLE`],
365 /// [`Error::DEPTH_EXCEEDED`]).
366 pub fn skip(&mut self) -> Result<(), Error> {
367 // A virtual root count of 1 makes loop termination uniform. The
368 // sentinel `u64::MAX` marks an open-ended (indefinite) scope that
369 // closes on a break byte instead of a counter reaching zero.
370 const OPEN: u64 = u64::MAX;
371 let mut stack = [0u64; SKIP_LIMIT];
372 stack[0] = 1;
373 let mut sp = 1usize;
374 loop {
375 match self.input.get(self.pos) {
376 None => return Err(Error::TRUNCATED),
377 Some(&b) if crate::head::is_break(b) => {
378 self.pos += 1;
379 match sp > 1 && stack[sp - 1] == OPEN {
380 true => sp -= 1,
381 false => return Err(Error::UNEXPECTED_BREAK),
382 }
383 }
384 Some(_) => {
385 let (major, arg, indef) = {
386 #[cfg(feature = "indefinite")]
387 {
388 self.next_head_ext()?
389 }
390 #[cfg(not(feature = "indefinite"))]
391 {
392 let (m, a) = self.next_head()?;
393 (m, a, false)
394 }
395 };
396 if indef {
397 #[cfg(not(feature = "indefinite"))]
398 return Err(Error::INDEFINITE_UNSUPPORTED);
399 #[cfg(feature = "indefinite")]
400 match major {
401 Major::Bytes | Major::Text => self.skip_chunks(major)?,
402 Major::Array | Major::Map => {
403 sp = Self::push(&mut stack, sp, OPEN)?;
404 continue;
405 }
406 _ => return Err(Error::INVALID_ADDITIONAL_INFO),
407 }
408 }
409 match major {
410 // Tags wrap one more item: leave the counter
411 // untouched so the tagged item is consumed
412 // before decrementing.
413 Major::Tag | Major::Unsigned | Major::Negative | Major::Simple => {}
414 Major::Bytes | Major::Text => {
415 let len = self.content_len(arg)?;
416 self.pos += len;
417 }
418 Major::Array | Major::Map => {
419 let items = match major {
420 Major::Map => arg.saturating_mul(2),
421 _ => arg,
422 };
423 if items > 0 {
424 sp = Self::push(&mut stack, sp, items)?;
425 continue;
426 }
427 }
428 }
429 }
430 }
431 // Closed item or closed scope: unwind completed scopes.
432 while sp > 0 {
433 if stack[sp - 1] == OPEN {
434 break; // waits for its break byte
435 }
436 let top = &mut stack[sp - 1];
437 *top -= 1;
438 if *top != 0 {
439 break;
440 }
441 sp -= 1;
442 }
443 if sp == 0 {
444 return Ok(());
445 }
446 }
447 }
448
449 /// Consumes definite chunks of an indefinite string until its break.
450 #[cfg(feature = "indefinite")]
451 fn skip_chunks(&mut self, major: Major) -> Result<(), Error> {
452 loop {
453 match self.input.get(self.pos) {
454 None => return Err(Error::TRUNCATED),
455 Some(&b) if crate::head::is_break(b) => {
456 self.pos += 1;
457 return Ok(());
458 }
459 Some(_) => {
460 let arg = self.expect_head(major)?;
461 let len = self.content_len(arg)?;
462 self.pos += len;
463 }
464 }
465 }
466 }
467
468 #[cold]
469 #[inline(never)]
470 fn push(stack: &mut [u64; SKIP_LIMIT], sp: usize, count: u64) -> Result<usize, Error> {
471 match sp < SKIP_LIMIT {
472 true => {
473 stack[sp] = count;
474 Ok(sp + 1)
475 }
476 false => Err(Error::DEPTH_EXCEEDED),
477 }
478 }
479}
480
481#[cfg(feature = "float")]
482mod float_impls {
483 use super::{Decoder, Error};
484 use crate::float::f32_of_f16_bits;
485 use crate::head::{Major, ext_len};
486
487 impl Decoder<'_> {
488 /// Decodes a half-, single-, or double-precision float into `f32`,
489 /// widening as needed.
490 ///
491 /// # Errors
492 ///
493 /// [`Error::TYPE_MISMATCH`] for non-float items.
494 pub fn f32(&mut self) -> Result<f32, Error> {
495 match self.float_bits()? {
496 (2, h) => Ok(f32_of_f16_bits(h as u16)),
497 (4, s) => Ok(f32::from_bits(s as u32)),
498 _ => Err(Error::TYPE_MISMATCH),
499 }
500 }
501
502 /// Decodes any float width into `f64`.
503 ///
504 /// # Errors
505 ///
506 /// As [`Decoder::f32`].
507 pub fn f64(&mut self) -> Result<f64, Error> {
508 match self.float_bits()? {
509 (2, h) => Ok(f64::from(f32_of_f16_bits(h as u16))),
510 (4, s) => Ok(f64::from(f32::from_bits(s as u32))),
511 (_, d) => Ok(f64::from_bits(d)),
512 }
513 }
514
515 /// Reads a float item, returning `(argument_bytes, payload_bits)`.
516 fn float_bits(&mut self) -> Result<(usize, u64), Error> {
517 let pos = self.pos;
518 let (major, arg) = self.next_head()?;
519 if major != Major::Simple {
520 return Err(Error::TYPE_MISMATCH);
521 }
522 let ai = self.input[pos] & 0x1f;
523 match ai {
524 25..=27 => Ok((ext_len(ai), arg)),
525 _ => Err(Error::TYPE_MISMATCH),
526 }
527 }
528 }
529}