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 /// `true` when the next byte is the break marker terminating an
58 /// indefinite-length item (RFC 8949 §3.2); does not consume anything.
59 #[inline]
60 #[must_use]
61 pub fn peek_break(&self) -> bool {
62 matches!(self.input.get(self.pos), Some(&b) if crate::head::is_break(b))
63 }
64
65 /// Raw initial byte of the next item, if any input remains; does not
66 /// consume anything. Lets callers inspect the additional-information
67 /// field (`byte & 0x1f`) before committing to a typed getter.
68 #[inline]
69 #[must_use]
70 pub fn peek_head_byte(&self) -> Option<u8> {
71 self.input.get(self.pos).copied()
72 }
73
74 /// Consumes the header of an indefinite-length item of major type
75 /// `want` (RFC 8949 §3.2), i.e. an initial byte with additional
76 /// information 31.
77 ///
78 /// # Errors
79 ///
80 /// [`Error::TYPE_MISMATCH`] unless the next item matches; structural
81 /// errors propagate.
82 #[cfg(any(feature = "indefinite", feature = "diagnostic"))]
83 pub fn expect_indef(&mut self, want: Major) -> Result<(), Error> {
84 let (major, _, indef) = self.next_head_ext()?;
85 match major == want && indef {
86 true => Ok(()),
87 false => Err(Error::TYPE_MISMATCH),
88 }
89 }
90
91 /// Consumes a break marker if present; reports whether one was there.
92 ///
93 /// # Errors
94 ///
95 /// [`Error::UNEXPECTED_BREAK`] is never produced here; the `Err` half
96 /// exists for API symmetry and currently cannot occur.
97 #[inline]
98 pub fn take_break(&mut self) -> Result<bool, Error> {
99 if self.peek_break() {
100 self.pos += 1;
101 Ok(true)
102 } else {
103 Ok(false)
104 }
105 }
106
107 /// Reads and consumes the next head.
108 #[inline]
109 fn next_head(&mut self) -> Result<(Major, u64), Error> {
110 let (major, arg, used) = read_head(&self.input[self.pos..])?;
111 self.pos += used;
112 Ok((major, arg))
113 }
114
115 /// Reads the next head, allowing indefinite lengths (used by the
116 /// `indefinite` and `diagnostic` features).
117 #[cfg(any(feature = "indefinite", feature = "diagnostic"))]
118 #[inline]
119 pub(crate) fn next_head_ext(&mut self) -> Result<(Major, u64, bool), Error> {
120 let (major, arg, used, indef) = crate::head::read_head_ext(&self.input[self.pos..])?;
121 self.pos += used;
122 Ok((major, arg, indef))
123 }
124
125 /// Requires the next item to be major type `want`, returning its argument.
126 #[inline]
127 fn expect_head(&mut self, want: Major) -> Result<u64, Error> {
128 let (major, arg) = self.next_head()?;
129 match major == want {
130 true => Ok(arg),
131 false => Err(Error::TYPE_MISMATCH),
132 }
133 }
134
135 /// Converts an argument into a `usize` content length within input bounds.
136 #[inline]
137 pub(crate) fn content_len(&self, arg: u64) -> Result<usize, Error> {
138 let len = usize::try_from(arg).map_err(|_| Error::TRUNCATED)?;
139 match len <= self.remaining() {
140 true => Ok(len),
141 false => Err(Error::TRUNCATED),
142 }
143 }
144
145 /// Decodes an unsigned integer, failing if it exceeds `T::MAX`.
146 #[inline]
147 fn uint_as<T: TryFrom<u64>>(&mut self) -> Result<T, Error> {
148 let v = self.expect_head(Major::Unsigned)?;
149 T::try_from(v).map_err(|_| Error::INTEGER_OUT_OF_RANGE)
150 }
151
152 /// Decodes a signed integer (`-1 - n` mapping), range-checked.
153 #[inline]
154 fn int_as<T: TryFrom<i64>>(&mut self) -> Result<T, Error> {
155 match self.peek_major() {
156 Some(Major::Unsigned) => {
157 let v = self.uint_as::<i64>()?;
158 T::try_from(v).map_err(|_| Error::INTEGER_OUT_OF_RANGE)
159 }
160 _ => {
161 let n = self.expect_head(Major::Negative)?;
162 // `-1 - n >= i64::MIN` requires n <= i64::MAX.
163 match i64::try_from(n).is_ok() {
164 true => T::try_from(-1 - n as i64).map_err(|_| Error::INTEGER_OUT_OF_RANGE),
165 false => Err(Error::INTEGER_OUT_OF_RANGE),
166 }
167 }
168 }
169 }
170
171 /// Decodes an unsigned integer that fits in `u8`.
172 ///
173 /// # Errors
174 ///
175 /// [`Error::TYPE_MISMATCH`] for non-integers; [`Error::INTEGER_OUT_OF_RANGE`]
176 /// when the value exceeds `u8::MAX`.
177 #[inline]
178 pub fn u8(&mut self) -> Result<u8, Error> {
179 self.uint_as()
180 }
181
182 /// Decodes an unsigned integer that fits in `u16`.
183 ///
184 /// # Errors
185 ///
186 /// As [`Decoder::u8`], with the wider target range.
187 #[inline]
188 pub fn u16(&mut self) -> Result<u16, Error> {
189 self.uint_as()
190 }
191
192 /// Decodes an unsigned integer that fits in `u32`.
193 ///
194 /// # Errors
195 ///
196 /// As [`Decoder::u8`], with the wider target range.
197 #[inline]
198 pub fn u32(&mut self) -> Result<u32, Error> {
199 self.uint_as()
200 }
201
202 /// Decodes any CBOR unsigned integer into `u64`.
203 ///
204 /// # Errors
205 ///
206 /// Returns [`Error::TYPE_MISMATCH`] for other major types.
207 #[inline]
208 pub fn u64(&mut self) -> Result<u64, Error> {
209 self.expect_head(Major::Unsigned)
210 }
211
212 /// Decodes a negative or non-negative integer into `i8`.
213 ///
214 /// # Errors
215 ///
216 /// [`Error::TYPE_MISMATCH`] for non-integers;
217 /// [`Error::INTEGER_OUT_OF_RANGE`] outside the `i8` range.
218 #[inline]
219 pub fn i8(&mut self) -> Result<i8, Error> {
220 self.int_as()
221 }
222
223 /// Decodes a signed integer into `i16`.
224 ///
225 /// # Errors
226 ///
227 /// As [`Decoder::i8`], with the wider target range.
228 #[inline]
229 pub fn i16(&mut self) -> Result<i16, Error> {
230 self.int_as()
231 }
232
233 /// Decodes a signed integer into `i32`.
234 ///
235 /// # Errors
236 ///
237 /// As [`Decoder::i8`], with the wider target range.
238 #[inline]
239 pub fn i32(&mut self) -> Result<i32, Error> {
240 self.int_as()
241 }
242
243 /// Decodes any CBOR integer (major types 0 and 1) into `i64`.
244 ///
245 /// # Errors
246 ///
247 /// [`Error::TYPE_MISMATCH`] for non-integers;
248 /// [`Error::INTEGER_OUT_OF_RANGE`] below `i64::MIN`.
249 #[inline]
250 pub fn i64(&mut self) -> Result<i64, Error> {
251 self.int_as()
252 }
253
254 /// Borrows a byte string's contents from the input.
255 ///
256 /// # Errors
257 ///
258 /// [`Error::TYPE_MISMATCH`] if not a byte string; [`Error::TRUNCATED`]
259 /// if the declared length exceeds the input.
260 #[inline]
261 pub fn bytes(&mut self) -> Result<&'a [u8], Error> {
262 self.bytes_of(Major::Bytes)
263 }
264
265 /// Borrows a text string from the input after validating UTF-8.
266 ///
267 /// # Errors
268 ///
269 /// [`Error::TYPE_MISMATCH`] if not a text string; [`Error::INVALID_UTF8`]
270 /// if the payload violates RFC 3629; [`Error::TRUNCATED`] on short input.
271 #[inline]
272 pub fn str(&mut self) -> Result<&'a str, Error> {
273 let raw = self.bytes_of(Major::Text)?;
274 core::str::from_utf8(raw).map_err(|_| Error::INVALID_UTF8)
275 }
276
277 #[inline]
278 pub(crate) fn bytes_of(&mut self, major: Major) -> Result<&'a [u8], Error> {
279 let arg = self.expect_head(major)?;
280 let len = self.content_len(arg)?;
281 let start = self.pos;
282 self.pos += len;
283 Ok(&self.input[start..start + len])
284 }
285
286 /// Decodes `true` or `false`.
287 ///
288 /// # Errors
289 ///
290 /// Returns [`Error::TYPE_MISMATCH`] for any other item.
291 #[inline]
292 pub fn bool(&mut self) -> Result<bool, Error> {
293 let s = self.simple_value()?;
294 match s.0 {
295 20 => Ok(false),
296 21 => Ok(true),
297 _ => Err(Error::TYPE_MISMATCH),
298 }
299 }
300
301 /// Decodes `null`; returns whether the value was null without consuming
302 /// anything else. Use [`Decoder::peek_major`] for generic lookahead.
303 ///
304 /// # Errors
305 ///
306 /// Propagates decode errors from malformed heads only.
307 #[inline]
308 pub fn is_null(&mut self) -> Result<bool, Error> {
309 match self.peek_simple() {
310 Some(s) if s.0 == Simple::NULL.0 => {
311 self.next_head()?;
312 Ok(true)
313 }
314 _ => Ok(false),
315 }
316 }
317
318 /// Decodes `undefined`.
319 ///
320 /// # Errors
321 ///
322 /// Returns [`Error::TYPE_MISMATCH`] for any other item.
323 #[inline]
324 pub fn undefined(&mut self) -> Result<(), Error> {
325 let s = self.simple_value()?;
326 match s.0 == Simple::UNDEFINED.0 {
327 true => Ok(()),
328 false => Err(Error::TYPE_MISMATCH),
329 }
330 }
331
332 /// Decodes any simple value (including booleans and null).
333 ///
334 /// # Errors
335 ///
336 /// [`Error::TYPE_MISMATCH`] for floats and non-major-7 items;
337 /// [`Error::INVALID_SIMPLE`] for two-byte encodings of values below 32.
338 #[inline]
339 pub fn simple(&mut self) -> Result<Simple, Error> {
340 self.simple_value()
341 }
342
343 #[inline]
344 fn peek_simple(&self) -> Option<Simple> {
345 match self.input.get(self.pos) {
346 Some(&b) if b >> 5 == 7 && b & 0x1f < 24 => Some(Simple(b & 0x1f)),
347 _ => None,
348 }
349 }
350
351 #[inline]
352 fn simple_value(&mut self) -> Result<Simple, Error> {
353 // Distinguish one-byte from two-byte form: values below 32 are
354 // forbidden in the two-byte encoding (RFC 8949 §3.3).
355 let two_byte = matches!(
356 self.input.get(self.pos),
357 Some(b) if b >> 5 == 7 && (b & 0x1f) == 24
358 );
359 // Floating-point widths (ai 25-27) carry IEEE 754 payloads, never
360 // simple values (RFC 8949 §3.3); the argument bits must not be
361 // reinterpreted as a simple value.
362 if matches!(
363 self.input.get(self.pos),
364 Some(b) if b >> 5 == 7 && matches!(b & 0x1f, 25..=27)
365 ) {
366 self.next_head()?;
367 return Err(Error::FLOAT_UNSUPPORTED);
368 }
369 let (major, arg) = self.next_head()?;
370 if major != Major::Simple {
371 return Err(Error::TYPE_MISMATCH);
372 }
373 match (arg, two_byte) {
374 (0..=23, false) | (32..=255, true) => Ok(Simple(arg as u8)),
375 (_, true) => Err(Error::INVALID_SIMPLE),
376 // ai 25–27 carry floating-point payloads, not simple values.
377 _ => Err(Error::FLOAT_UNSUPPORTED),
378 }
379 }
380
381 /// Reads a tag number; the tagged item follows immediately.
382 ///
383 /// Tag semantics are application concerns (RFC 8949 §3.4); this returns
384 /// only the number.
385 ///
386 /// # Errors
387 ///
388 /// Returns [`Error::TYPE_MISMATCH`] if the item is not a tag.
389 #[inline]
390 pub fn tag(&mut self) -> Result<u64, Error> {
391 self.expect_head(Major::Tag)
392 }
393
394 /// Reads an array header, returning the number of following items.
395 ///
396 /// # Errors
397 ///
398 /// Returns [`Error::TYPE_MISMATCH`] if the item is not an array.
399 #[inline]
400 pub fn array_len(&mut self) -> Result<usize, Error> {
401 let n = self.expect_head(Major::Array)?;
402 usize::try_from(n).map_err(|_| Error::INTEGER_OUT_OF_RANGE)
403 }
404
405 /// Reads a map header, returning the number of following key/value pairs.
406 ///
407 /// # Errors
408 ///
409 /// Returns [`Error::TYPE_MISMATCH`] if the item is not a map.
410 #[inline]
411 pub fn map_len(&mut self) -> Result<usize, Error> {
412 let n = self.expect_head(Major::Map)?;
413 usize::try_from(n).map_err(|_| Error::INTEGER_OUT_OF_RANGE)
414 }
415
416 /// Consumes exactly one complete data item, whatever its type.
417 ///
418 /// Nested containers are traversed iteratively up to [`SKIP_LIMIT`]
419 /// levels deep; deeper input yields [`Error::DEPTH_EXCEEDED`].
420 ///
421 /// # Errors
422 ///
423 /// Any structural error ([`Error::TRUNCATED`],
424 /// [`Error::INVALID_ADDITIONAL_INFO`], [`Error::INVALID_SIMPLE`],
425 /// [`Error::DEPTH_EXCEEDED`]).
426 pub fn skip(&mut self) -> Result<(), Error> {
427 // A virtual root count of 1 makes loop termination uniform. The
428 // sentinel marks an open-ended (indefinite) scope that closes on a
429 // break byte instead of a counter reaching zero.
430 //
431 // Counters are u32: a container declaring more than `u32::MAX`
432 // items hits `TRUNCATED` long before the counter could matter
433 // (each item occupies at least one byte), so narrowing the counter
434 // cannot change any outcome — and halves the stack's zeroing cost.
435 type Count = u32;
436 const OPEN: Count = Count::MAX;
437 const CLAMP: u64 = (Count::MAX - 1) as u64;
438 let mut stack = [0u32; SKIP_LIMIT];
439 stack[0] = 1;
440 let mut sp = 1usize;
441 loop {
442 match self.input.get(self.pos) {
443 None => return Err(Error::TRUNCATED),
444 Some(&b) if crate::head::is_break(b) => {
445 self.pos += 1;
446 match sp > 1 && stack[sp - 1] == OPEN {
447 true => sp -= 1,
448 false => return Err(Error::UNEXPECTED_BREAK),
449 }
450 }
451 Some(_) => {
452 let (major, arg, indef) = {
453 #[cfg(feature = "indefinite")]
454 {
455 self.next_head_ext()?
456 }
457 #[cfg(not(feature = "indefinite"))]
458 {
459 let (m, a) = self.next_head()?;
460 (m, a, false)
461 }
462 };
463 if indef {
464 #[cfg(not(feature = "indefinite"))]
465 return Err(Error::INDEFINITE_UNSUPPORTED);
466 #[cfg(feature = "indefinite")]
467 match major {
468 Major::Bytes | Major::Text => self.skip_chunks(major)?,
469 Major::Array | Major::Map => {
470 sp = Self::push(&mut stack, sp, OPEN)?;
471 continue;
472 }
473 _ => return Err(Error::INVALID_ADDITIONAL_INFO),
474 }
475 }
476 match major {
477 // A tag wraps exactly one more item (RFC 8949
478 // section 3.4): defer the counter decrement by
479 // looping straight to the next item, so the
480 // tagged payload is consumed as part of this one.
481 Major::Tag => continue,
482 Major::Unsigned | Major::Negative | Major::Simple => {}
483 Major::Bytes | Major::Text => {
484 let len = self.content_len(arg)?;
485 self.pos += len;
486 }
487 Major::Array | Major::Map => {
488 let items = match major {
489 Major::Map => arg.saturating_mul(2),
490 _ => arg,
491 };
492 // Clamp before narrowing: see the u32 note on
493 // the stack declaration above.
494 if items > 0 {
495 sp = Self::push(&mut stack, sp, items.min(CLAMP) as Count)?;
496 continue;
497 }
498 }
499 }
500 }
501 }
502 // Closed item or closed scope: unwind completed scopes.
503 while sp > 0 {
504 if stack[sp - 1] == OPEN {
505 break; // waits for its break byte
506 }
507 let top = &mut stack[sp - 1];
508 *top -= 1;
509 if *top != 0 {
510 break;
511 }
512 sp -= 1;
513 }
514 if sp == 0 {
515 return Ok(());
516 }
517 }
518 }
519
520 /// Consumes definite chunks of an indefinite string until its break.
521 #[cfg(feature = "indefinite")]
522 fn skip_chunks(&mut self, major: Major) -> Result<(), Error> {
523 loop {
524 match self.input.get(self.pos) {
525 None => return Err(Error::TRUNCATED),
526 Some(&b) if crate::head::is_break(b) => {
527 self.pos += 1;
528 return Ok(());
529 }
530 Some(_) => {
531 let arg = self.expect_head(major)?;
532 let len = self.content_len(arg)?;
533 self.pos += len;
534 }
535 }
536 }
537 }
538
539 #[cold]
540 #[inline(never)]
541 fn push(stack: &mut [u32; SKIP_LIMIT], sp: usize, count: u32) -> Result<usize, Error> {
542 match sp < SKIP_LIMIT {
543 true => {
544 stack[sp] = count;
545 Ok(sp + 1)
546 }
547 false => Err(Error::DEPTH_EXCEEDED),
548 }
549 }
550}
551
552#[cfg(feature = "float")]
553mod float_impls {
554 use super::{Decoder, Error};
555 use crate::float::f32_of_f16_bits;
556 use crate::head::{Major, ext_len};
557
558 impl Decoder<'_> {
559 /// Decodes a half-, single-, or double-precision float into `f32`,
560 /// widening as needed.
561 ///
562 /// # Errors
563 ///
564 /// [`Error::TYPE_MISMATCH`] for non-float items.
565 pub fn f32(&mut self) -> Result<f32, Error> {
566 match self.float_bits()? {
567 (2, h) => Ok(f32_of_f16_bits(h as u16)),
568 (4, s) => Ok(f32::from_bits(s as u32)),
569 _ => Err(Error::TYPE_MISMATCH),
570 }
571 }
572
573 /// Decodes any float width into `f64`.
574 ///
575 /// # Errors
576 ///
577 /// As [`Decoder::f32`].
578 pub fn f64(&mut self) -> Result<f64, Error> {
579 match self.float_bits()? {
580 (2, h) => Ok(f64::from(f32_of_f16_bits(h as u16))),
581 (4, s) => Ok(f64::from(f32::from_bits(s as u32))),
582 (_, d) => Ok(f64::from_bits(d)),
583 }
584 }
585
586 /// Reads a float item, returning `(argument_bytes, payload_bits)`.
587 fn float_bits(&mut self) -> Result<(usize, u64), Error> {
588 let pos = self.pos;
589 let (major, arg) = self.next_head()?;
590 if major != Major::Simple {
591 return Err(Error::TYPE_MISMATCH);
592 }
593 let ai = self.input[pos] & 0x1f;
594 match ai {
595 25..=27 => Ok((ext_len(ai), arg)),
596 _ => Err(Error::TYPE_MISMATCH),
597 }
598 }
599 }
600}