Skip to main content

minicbor/decode/
decoder.rs

1#![allow(clippy::unusual_byte_groupings)]
2
3use crate::{ARRAY, BREAK, BYTES, MAP, SIMPLE, TAGGED, TEXT, SIGNED, UNSIGNED};
4use crate::data::{Int, Tag, Type};
5use crate::decode::{Decode, Error};
6use core::{marker, str};
7
8/// A non-allocating CBOR decoder.
9#[derive(Debug, Clone)]
10pub struct Decoder<'b> {
11    buf: &'b [u8],
12    pos: usize
13}
14
15impl<'b> Decoder<'b> {
16    /// Construct a `Decoder` for the given byte slice.
17    pub fn new(bytes: &'b [u8]) -> Self {
18        Decoder { buf: bytes, pos: 0 }
19    }
20
21    /// Decode any type that implements [`Decode`].
22    pub fn decode<T: Decode<'b, ()>>(&mut self) -> Result<T, Error> {
23        T::decode(self, &mut ())
24    }
25
26    /// Decode any type that implements [`Decode`].
27    pub fn decode_with<C, T: Decode<'b, C>>(&mut self, ctx: &mut C) -> Result<T, Error> {
28        T::decode(self, ctx)
29    }
30
31    /// Get the current decode position.
32    pub fn position(&self) -> usize {
33        self.pos
34    }
35
36    /// Set the current decode position.
37    pub fn set_position(&mut self, pos: usize) {
38        self.pos = pos
39    }
40
41    /// Get a reference to the input bytes.
42    pub fn input(&self) -> &'b [u8] {
43        self.buf
44    }
45
46    /// Get a decoding probe to look ahead what is coming next.
47    ///
48    /// This will not affect the decoding state of `self` and after the
49    /// returned `Probe` has been dropped, decoding can continue from
50    /// its current position as if `probe` was never called.
51    pub fn probe<'a>(&'a mut self) -> Probe<'a, 'b> {
52        Probe {
53            decoder: self.clone(),
54            _marker: marker::PhantomData
55        }
56    }
57
58    /// Decode a `bool` value.
59    pub fn bool(&mut self) -> Result<bool, Error> {
60        let p = self.pos;
61        match self.read()? {
62            0xf4 => Ok(false),
63            0xf5 => Ok(true),
64            b    => Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected bool"))
65        }
66    }
67
68    /// Decode a `u8` value.
69    pub fn u8(&mut self) -> Result<u8, Error> {
70        let p = self.pos;
71        match self.read()? {
72            n @ 0 ..= 0x17 => Ok(n),
73            0x18           => self.read(),
74            0x19           => self.read_array().map(u16::from_be_bytes).and_then(|n| try_as(n, "when converting u16 to u8", p)),
75            0x1a           => self.read_array().map(u32::from_be_bytes).and_then(|n| try_as(n, "when converting u32 to u8", p)),
76            0x1b           => self.read_array().map(u64::from_be_bytes).and_then(|n| try_as(n, "when converting u64 to u8", p)),
77            b              => Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected u8"))
78        }
79    }
80
81    /// Decode a `u16` value.
82    pub fn u16(&mut self) -> Result<u16, Error> {
83        let p = self.pos;
84        match self.read()? {
85            n @ 0 ..= 0x17 => Ok(u16::from(n)),
86            0x18           => self.read().map(u16::from),
87            0x19           => self.read_array().map(u16::from_be_bytes),
88            0x1a           => self.read_array().map(u32::from_be_bytes).and_then(|n| try_as(n, "when converting u32 to u16", p)),
89            0x1b           => self.read_array().map(u64::from_be_bytes).and_then(|n| try_as(n, "when converting u64 to u16", p)),
90            b              => Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected u16"))
91        }
92    }
93
94    /// Decode a `u32` value.
95    pub fn u32(&mut self) -> Result<u32, Error> {
96        let p = self.pos;
97        match self.read()? {
98            n @ 0 ..= 0x17 => Ok(u32::from(n)),
99            0x18           => self.read().map(u32::from),
100            0x19           => self.read_array().map(u16::from_be_bytes).map(u32::from),
101            0x1a           => self.read_array().map(u32::from_be_bytes),
102            0x1b           => self.read_array().map(u64::from_be_bytes).and_then(|n| try_as(n, "when converting u64 to u32", p)),
103            b              => Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected u32"))
104        }
105    }
106
107    /// Decode a `u64` value.
108    pub fn u64(&mut self) -> Result<u64, Error> {
109        let p = self.pos;
110        let n = self.read()?;
111        self.unsigned(n, p)
112    }
113
114    /// Decode an `i8` value.
115    pub fn i8(&mut self) -> Result<i8, Error> {
116        let p = self.pos;
117        match self.read()? {
118            n @ 0x00 ..= 0x17 => Ok(n as i8),
119            0x18              => self.read().and_then(|n| try_as(n, "when converting u8 to i8", p)),
120            0x19              => self.read_array().map(u16::from_be_bytes).and_then(|n| try_as(n, "when converting u16 to i8", p)),
121            0x1a              => self.read_array().map(u32::from_be_bytes).and_then(|n| try_as(n, "when converting u32 to i8", p)),
122            0x1b              => self.read_array().map(u64::from_be_bytes).and_then(|n| try_as(n, "when converting u64 to i8", p)),
123            n @ 0x20 ..= 0x37 => Ok(-1 - (n - 0x20) as i8),
124            0x38              => self.read().and_then(|n| try_as(n, "when converting u8 to i8", p).map(|n: i8| -1 - n)),
125            0x39              => self.read_array().map(u16::from_be_bytes).and_then(|n| try_as(n, "when converting u16 to i8", p).map(|n: i8| -1 - n)),
126            0x3a              => self.read_array().map(u32::from_be_bytes).and_then(|n| try_as(n, "when converting u32 to i8", p).map(|n: i8| -1 - n)),
127            0x3b              => self.read_array().map(u64::from_be_bytes).and_then(|n| try_as(n, "when converting u64 to i8", p).map(|n: i8| -1 - n)),
128            b                 => Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected i8"))
129        }
130    }
131
132    /// Decode an `i16` value.
133    pub fn i16(&mut self) -> Result<i16, Error> {
134        let p = self.pos;
135        match self.read()? {
136            n @ 0x00 ..= 0x17 => Ok(i16::from(n)),
137            0x18              => self.read().map(i16::from),
138            0x19              => self.read_array().map(u16::from_be_bytes).and_then(|n| try_as(n, "when converting u16 to i16", p)),
139            0x1a              => self.read_array().map(u32::from_be_bytes).and_then(|n| try_as(n, "when converting u32 to i16", p)),
140            0x1b              => self.read_array().map(u64::from_be_bytes).and_then(|n| try_as(n, "when converting u64 to i16", p)),
141            n @ 0x20 ..= 0x37 => Ok(-1 - i16::from(n - 0x20)),
142            0x38              => self.read().map(|n| -1 - i16::from(n)),
143            0x39              => self.read_array().map(u16::from_be_bytes).and_then(|n| try_as(n, "when converting u16 to i16", p).map(|n: i16| -1 - n)),
144            0x3a              => self.read_array().map(u32::from_be_bytes).and_then(|n| try_as(n, "when converting u32 to i16", p).map(|n: i16| -1 - n)),
145            0x3b              => self.read_array().map(u64::from_be_bytes).and_then(|n| try_as(n, "when converting u64 to i16", p).map(|n: i16| -1 - n)),
146            b                 => Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected i16"))
147        }
148    }
149
150    /// Decode an `i32` value.
151    pub fn i32(&mut self) -> Result<i32, Error> {
152        let p = self.pos;
153        match self.read()? {
154            n @ 0x00 ..= 0x17 => Ok(i32::from(n)),
155            0x18              => self.read().map(i32::from),
156            0x19              => self.read_array().map(u16::from_be_bytes).map(i32::from),
157            0x1a              => self.read_array().map(u32::from_be_bytes).and_then(|n| try_as(n, "when converting u32 to i32", p)),
158            0x1b              => self.read_array().map(u64::from_be_bytes).and_then(|n| try_as(n, "when converting u64 to i32", p)),
159            n @ 0x20 ..= 0x37 => Ok(-1 - i32::from(n - 0x20)),
160            0x38              => self.read().map(|n| -1 - i32::from(n)),
161            0x39              => self.read_array().map(u16::from_be_bytes).map(|n| -1 - i32::from(n)),
162            0x3a              => self.read_array().map(u32::from_be_bytes).and_then(|n| try_as(n, "when converting u32 to i32", p).map(|n: i32| -1 - n)),
163            0x3b              => self.read_array().map(u64::from_be_bytes).and_then(|n| try_as(n, "when converting u64 to i32", p).map(|n: i32| -1 - n)),
164            b                 => Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected i32"))
165        }
166    }
167
168    /// Decode an `i64` value.
169    pub fn i64(&mut self) -> Result<i64, Error> {
170        let p = self.pos;
171        match self.read()? {
172            n @ 0x00 ..= 0x17 => Ok(i64::from(n)),
173            0x18              => self.read().map(i64::from),
174            0x19              => self.read_array().map(u16::from_be_bytes).map(i64::from),
175            0x1a              => self.read_array().map(u32::from_be_bytes).map(i64::from),
176            0x1b              => self.read_array().map(u64::from_be_bytes).and_then(|n| try_as(n, "when converting u64 to i64", p)),
177            n @ 0x20 ..= 0x37 => Ok(-1 - i64::from(n - 0x20)),
178            0x38              => self.read().map(|n| -1 - i64::from(n)),
179            0x39              => self.read_array().map(u16::from_be_bytes).map(|n| -1 - i64::from(n)),
180            0x3a              => self.read_array().map(u32::from_be_bytes).map(|n| -1 - i64::from(n)),
181            0x3b              => self.read_array().map(u64::from_be_bytes).and_then(|n| try_as(n, "when converting u64 to i64", p).map(|n: i64| -1 - n)),
182            b                 => Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected i64"))
183        }
184    }
185
186    /// Decode a CBOR integer.
187    ///
188    /// See [`Int`] for details regarding the value range of CBOR integers.
189    pub fn int(&mut self) -> Result<Int, Error> {
190        let p = self.pos;
191        match self.read()? {
192            n @ 0x00 ..= 0x17 => Ok(Int::pos(n)),
193            0x18              => self.read().map(Int::pos),
194            0x19              => self.read_array().map(u16::from_be_bytes).map(Int::pos),
195            0x1a              => self.read_array().map(u32::from_be_bytes).map(Int::pos),
196            0x1b              => self.read_array().map(u64::from_be_bytes).map(Int::pos),
197            n @ 0x20 ..= 0x37 => Ok(Int::neg(n - 0x20)),
198            0x38              => self.read().map(Int::neg),
199            0x39              => self.read_array().map(u16::from_be_bytes).map(Int::neg),
200            0x3a              => self.read_array().map(u32::from_be_bytes).map(Int::neg),
201            0x3b              => self.read_array().map(u64::from_be_bytes).map(Int::neg),
202            b                 => Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected int"))
203        }
204    }
205
206    /// Decode a half float (`f16`) and return it in an `f32`.
207    ///
208    /// Only available when the feature `half` is present.
209    #[cfg(feature = "half")]
210    pub fn f16(&mut self) -> Result<f32, Error> {
211        let p = self.pos;
212        let b = self.read()?;
213        if 0xf9 != b {
214            return Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected f16"))
215        }
216        Ok(half::f16::from_bits(u16::from_be_bytes(self.read_array()?)).to_f32())
217    }
218
219    /// Decode an `f32` value.
220    pub fn f32(&mut self) -> Result<f32, Error> {
221        let p = self.pos;
222        match self.current()? {
223            #[cfg(feature = "half")]
224            0xf9 => self.f16(),
225            0xfa => {
226                self.read()?;
227                Ok(f32::from_be_bytes(self.read_array()?))
228            }
229            b => Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected f32"))
230        }
231    }
232
233    /// Decode an `f64` value.
234    pub fn f64(&mut self) -> Result<f64, Error> {
235        let p = self.pos;
236        match self.current()? {
237            #[cfg(feature = "half")]
238            0xf9 => self.f16().map(f64::from),
239            0xfa => self.f32().map(f64::from),
240            0xfb => {
241                self.read()?;
242                Ok(f64::from_be_bytes(self.read_array()?))
243            }
244            b => Err(Error::type_mismatch(self.type_of(b)?).at(p).with_message("expected f64"))
245        }
246    }
247
248    /// Decode a `char` value.
249    pub fn char(&mut self) -> Result<char, Error> {
250        let p = self.pos;
251        let n = self.u32()?;
252        char::from_u32(n).ok_or_else(|| Error::invalid_char(n).at(p))
253    }
254
255    /// Decode a byte slice.
256    ///
257    /// This only decodes byte slices of definite lengths.
258    /// See [`Decoder::bytes_iter`] for indefinite byte slice support.
259    pub fn bytes(&mut self) -> Result<&'b [u8], Error> {
260        let p = self.pos;
261        let b = self.read()?;
262        if BYTES != type_of(b) || info_of(b) == 31 {
263            return Err(Error::type_mismatch(self.type_of(b)?)
264                .with_message("expected bytes (definite length)")
265                .at(p))
266        }
267        let n = u64_to_usize(self.unsigned(info_of(b), p)?, p)?;
268        self.read_slice(n)
269    }
270
271    /// Iterate over byte slices.
272    ///
273    /// This supports indefinite byte slices by returing a byte slice on each
274    /// iterator step. If a single definite slice is decoded the iterator will
275    /// only yield one item.
276    pub fn bytes_iter(&mut self) -> Result<BytesIter<'_, 'b>, Error> {
277        let p = self.pos;
278        let b = self.read()?;
279        if BYTES != type_of(b) {
280            return Err(Error::type_mismatch(self.type_of(b)?)
281                .with_message("expected bytes")
282                .at(p))
283        }
284        match info_of(b) {
285            31 => Ok(BytesIter { decoder: self, state: State::Indef }),
286            n  => {
287                let len = u64_to_usize(self.unsigned(n, p)?, p)?;
288                Ok(BytesIter { decoder: self, state: State::Def(len) })
289            }
290        }
291    }
292
293    /// Decode a string slice.
294    ///
295    /// This only decodes string slices of definite lengths.
296    /// See [`Decoder::str_iter`] for indefinite string slice support.
297    pub fn str(&mut self) -> Result<&'b str, Error> {
298        let p = self.pos;
299        let b = self.read()?;
300        if TEXT != type_of(b) || info_of(b) == 31 {
301            return Err(Error::type_mismatch(self.type_of(b)?)
302                .with_message("expected text (definite length)")
303                .at(p))
304        }
305        let n = u64_to_usize(self.unsigned(info_of(b), p)?, p)?;
306        let d = self.read_slice(n)?;
307        str::from_utf8(d).map_err(|e| Error::utf8(e).at(p))
308    }
309
310    /// Iterate over string slices.
311    ///
312    /// This supports indefinite string slices by returing a string slice on
313    /// each iterator step. If a single definite slice is decoded the iterator
314    /// will only yield one item.
315    pub fn str_iter(&mut self) -> Result<StrIter<'_, 'b>, Error> {
316        let p = self.pos;
317        let b = self.read()?;
318        if TEXT != type_of(b) {
319            return Err(Error::type_mismatch(self.type_of(b)?)
320                .with_message("expected text")
321                .at(p))
322        }
323        match info_of(b) {
324            31 => Ok(StrIter { decoder: self, state: State::Indef, pos: p }),
325            n  => {
326                let len = u64_to_usize(self.unsigned(n, p)?, p)?;
327                Ok(StrIter { decoder: self, state: State::Def(len), pos: p })
328            }
329        }
330    }
331
332    /// Begin decoding an array.
333    ///
334    /// CBOR arrays are heterogenous collections and may be of indefinite
335    /// length. If the length is known it is returned as a `Some`, for
336    /// indefinite arrays a `None` is returned.
337    pub fn array(&mut self) -> Result<Option<u64>, Error> {
338        let p = self.pos;
339        let b = self.read()?;
340        if ARRAY != type_of(b) {
341            return Err(Error::type_mismatch(self.type_of(b)?)
342                .with_message("expected array")
343                .at(p))
344        }
345        match info_of(b) {
346            31 => Ok(None),
347            n  => Ok(Some(self.unsigned(n, p)?))
348        }
349    }
350
351    /// Iterate over all array elements.
352    ///
353    /// This supports indefinite and definite length arrays and uses the
354    /// [`Decode`] trait to decode each element. Consequently *only
355    /// homogenous arrays are supported by this method*.
356    pub fn array_iter<T>(&mut self) -> Result<ArrayIter<'_, 'b, T>, Error>
357    where
358        T: Decode<'b, ()>
359    {
360        let len = self.array()?;
361        Ok(ArrayIter { decoder: self, state: len.into(), _mark: marker::PhantomData })
362    }
363
364    /// Iterate over all array elements.
365    ///
366    /// This supports indefinite and definite length arrays and uses the
367    /// [`Decode`] trait to decode each element. Consequently *only
368    /// homogenous arrays are supported by this method*.
369    pub fn array_iter_with<'a, C, T>(&'a mut self, ctx: &'a mut C) -> Result<ArrayIterWithCtx<'a, 'b, C, T>, Error>
370    where
371        T: Decode<'b, C>
372    {
373        let len = self.array()?;
374        Ok(ArrayIterWithCtx { decoder: self, ctx, state: len.into(), _mark: marker::PhantomData })
375    }
376
377    /// Begin decoding a map.
378    ///
379    /// CBOR maps are heterogenous collections (both in keys and in values)
380    /// and may be of indefinite length. If the length is known it is returned
381    /// as a `Some`, for indefinite maps a `None` is returned.
382    pub fn map(&mut self) -> Result<Option<u64>, Error> {
383        let p = self.pos;
384        let b = self.read()?;
385        if MAP != type_of(b) {
386            return Err(Error::type_mismatch(self.type_of(b)?)
387                .with_message("expected map")
388                .at(p))
389        }
390        match info_of(b) {
391            31 => Ok(None),
392            n  => Ok(Some(self.unsigned(n, p)?))
393        }
394    }
395
396    /// Iterate over all map entries.
397    ///
398    /// This supports indefinite and definite length maps and uses the
399    /// [`Decode`] trait to decode each key and value. Consequently *only
400    /// homogenous maps are supported by this method*.
401    pub fn map_iter<K, V>(&mut self) -> Result<MapIter<'_, 'b, K, V>, Error>
402    where
403        K: Decode<'b, ()>,
404        V: Decode<'b, ()>
405    {
406        let len = self.map()?;
407        Ok(MapIter { decoder: self, state: len.into(), _mark: marker::PhantomData })
408    }
409
410    /// Iterate over all map entries.
411    ///
412    /// This supports indefinite and definite length maps and uses the
413    /// [`Decode`] trait to decode each key and value. Consequently *only
414    /// homogenous maps are supported by this method*.
415    pub fn map_iter_with<'a, C, K, V>(&'a mut self, ctx: &'a mut C) -> Result<MapIterWithCtx<'a, 'b, C, K, V>, Error>
416    where
417        K: Decode<'b, C>,
418        V: Decode<'b, C>
419    {
420        let len = self.map()?;
421        Ok(MapIterWithCtx { decoder: self, ctx, state: len.into(), _mark: marker::PhantomData })
422    }
423
424    /// Decode a CBOR tag.
425    pub fn tag(&mut self) -> Result<Tag, Error> {
426        let p = self.pos;
427        let b = self.read()?;
428        if TAGGED != type_of(b) {
429            return Err(Error::type_mismatch(self.type_of(b)?)
430                .with_message("expected tag")
431                .at(p))
432        }
433        self.unsigned(info_of(b), p).map(Tag::new)
434    }
435
436    /// Decode a CBOR null value.
437    pub fn null(&mut self) -> Result<(), Error> {
438        let p = self.pos;
439        match self.read()? {
440            0xf6 => Ok(()),
441            n    => Err(Error::type_mismatch(self.type_of(n)?)
442                .with_message("expected null")
443                .at(p))
444        }
445    }
446
447    /// Decode a CBOR undefined value.
448    pub fn undefined(&mut self) -> Result<(), Error> {
449        let p = self.pos;
450        match self.read()? {
451            0xf7 => Ok(()),
452            n    => Err(Error::type_mismatch(self.type_of(n)?)
453                .with_message("expected undefined")
454                .at(p))
455        }
456    }
457
458    /// Decode a CBOR simple value.
459    pub fn simple(&mut self) -> Result<u8, Error> {
460        let p = self.pos;
461        match self.read()? {
462            n @ SIMPLE ..= 0xf3 => Ok(n - SIMPLE),
463            0xf8 => self.read(),
464            n    => Err(Error::type_mismatch(self.type_of(n)?)
465                .with_message("expected simple value")
466                .at(p))
467        }
468    }
469
470    /// Inspect the CBOR type at the current position.
471    pub fn datatype(&self) -> Result<Type, Error> {
472        self.type_of(self.current()?)
473    }
474
475    /// Iterate over a series of CBOR tokens.
476    #[cfg(feature = "half")]
477    pub fn tokens<'a>(&'a mut self) -> crate::decode::Tokenizer<'a, 'b> {
478        crate::decode::Tokenizer::from(self)
479    }
480
481    /// Skip over the current CBOR value.
482    #[cfg(feature = "alloc")]
483    pub fn skip(&mut self) -> Result<(), Error> {
484        // Unless we encounter indefinite-length arrays or maps inside of regular
485        // maps or arrays we only need to count how many more CBOR items we need
486        // to skip (initially starting with 1) or how many more break bytes we
487        // need to expect (initially starting with 0).
488        //
489        // If we do need to handle indefinite items (other than bytes or strings),
490        // inside of regular maps or arrays, we switch to using a stack of length
491        // information, starting with the remaining number of potential breaks we
492        // are still expecting and the number of items we still need to skip over
493        // at that point.
494
495        let mut nrounds = 1u64; // number of iterations over array and map elements
496        let mut irounds = 0u64; // number of indefinite iterations
497        let mut stack: alloc::vec::Vec<Option<u64>> = alloc::vec::Vec::new();
498
499        while nrounds > 0 || irounds > 0 || !stack.is_empty() {
500            match self.current()? {
501                UNSIGNED ..= 0x1b => { self.u64()?; }
502                SIGNED   ..= 0x3b => { self.int()?; }
503                BYTES    ..= 0x5f => { for v in self.bytes_iter()? { v?; } }
504                TEXT     ..= 0x7f => { for v in self.str_iter()? { v?; } }
505                ARRAY    ..= 0x9f =>
506                    match self.array()? {
507                        Some(0) => {}
508                        Some(n) =>
509                            if nrounds == 0 && irounds == 0 {
510                                stack.push(Some(n))
511                            } else {
512                                nrounds = nrounds.saturating_add(n)
513                            }
514                        None =>
515                            if nrounds == 0 && irounds == 0 {
516                                stack.push(None)
517                            } else if nrounds < 2 {
518                                irounds = irounds.saturating_add(1)
519                            } else {
520                                for _ in 0 .. irounds {
521                                    stack.push(None)
522                                }
523                                stack.push(Some(nrounds - 1));
524                                stack.push(None);
525                                nrounds = 0;
526                                irounds = 0
527                            }
528                    }
529                MAP ..= 0xbf =>
530                    match self.map()? {
531                        Some(0) => {}
532                        Some(n) =>
533                            if nrounds == 0 && irounds == 0 {
534                                stack.push(Some(n.saturating_mul(2)))
535                            } else {
536                                nrounds = nrounds.saturating_add(n.saturating_mul(2))
537                            }
538                        None =>
539                            if nrounds == 0 && irounds == 0 {
540                                stack.push(None)
541                            } else if nrounds < 2 {
542                                irounds = irounds.saturating_add(1)
543                            } else {
544                                for _ in 0 .. irounds {
545                                    stack.push(None)
546                                }
547                                stack.push(Some(nrounds - 1));
548                                stack.push(None);
549                                nrounds = 0;
550                                irounds = 0
551                            }
552                    }
553                TAGGED ..= 0xdb => {
554                    let p = self.pos;
555                    self.read().and_then(|n| self.unsigned(info_of(n), p))?;
556                    continue
557                }
558                SIMPLE ..= 0xfb => {
559                    let p = self.pos;
560                    self.read().and_then(|n| self.unsigned(info_of(n), p))?;
561                }
562                BREAK => {
563                    self.read()?;
564                    if nrounds == 0 && irounds == 0 {
565                        if let Some(None) = stack.last() {
566                            stack.pop();
567                        }
568                    } else {
569                        irounds = irounds.saturating_sub(1)
570                    }
571                }
572                other => return Err(Error::type_mismatch(self.type_of(other)?)
573                    .at(self.pos)
574                    .with_message("unknown type"))
575            }
576            if nrounds == 0 && irounds == 0 {
577                while let Some(Some(0)) = stack.last() {
578                     stack.pop();
579                }
580                match stack.last_mut() {
581                    Some(Some(n)) => { *n -= 1 }
582                    Some(None)    => {}
583                    None          => break
584                }
585            } else {
586                nrounds = nrounds.saturating_sub(1)
587            }
588        }
589
590        Ok(())
591    }
592
593    /// Skip over the current CBOR value.
594    ///
595    /// Without feature `alloc`, skipping over maps or arrays that contain an
596    /// indefinite-length map or array will return an error.
597    #[cfg(not(feature = "alloc"))]
598    pub fn skip(&mut self) -> Result<(), Error> {
599        let mut nrounds = 1u64; // number of iterations over array and map elements
600        let mut irounds = 0u64; // number of indefinite iterations
601
602        let error_msg =
603            "arrays and maps of indefinite length inside of \
604            regular arrays or maps require feature flag `alloc`";
605
606        while nrounds > 0 || irounds > 0 {
607            match self.current()? {
608                UNSIGNED ..= 0x1b => { self.u64()?; }
609                SIGNED   ..= 0x3b => { self.int()?; }
610                BYTES    ..= 0x5f => { for v in self.bytes_iter()? { v?; } }
611                TEXT     ..= 0x7f => { for v in self.str_iter()? { v?; } }
612                ARRAY    ..= 0x9f =>
613                    if let Some(n) = self.array()? {
614                        nrounds = nrounds.saturating_add(n)
615                    } else if nrounds < 2 {
616                        irounds = irounds.saturating_add(1)
617                    } else {
618                        return Err(Error::message(error_msg))
619                    }
620                MAP ..= 0xbf =>
621                    if let Some(n) = self.map()? {
622                        nrounds = nrounds.saturating_add(n.saturating_mul(2))
623                    } else if nrounds < 2 {
624                        irounds = irounds.saturating_add(1)
625                    } else {
626                        return Err(Error::message(error_msg))
627                    }
628                TAGGED ..= 0xdb => {
629                    let p = self.pos;
630                    self.read().and_then(|n| self.unsigned(info_of(n), p))?;
631                    continue
632                }
633                SIMPLE ..= 0xfb => {
634                    let p = self.pos;
635                    self.read().and_then(|n| self.unsigned(info_of(n), p))?;
636                }
637                BREAK => {
638                    self.read()?;
639                    irounds = irounds.saturating_sub(1)
640                }
641                other => return Err(Error::type_mismatch(self.type_of(other)?)
642                    .at(self.pos)
643                    .with_message("not supported"))
644            }
645            nrounds = nrounds.saturating_sub(1)
646        }
647
648        Ok(())
649    }
650
651    /// Decode a `u64` value beginning with `b`.
652    pub(crate) fn unsigned(&mut self, b: u8, p: usize) -> Result<u64, Error> {
653        match b {
654            n @ 0 ..= 0x17 => Ok(u64::from(n)),
655            0x18 => self.read().map(u64::from),
656            0x19 => self.read_array().map(u16::from_be_bytes).map(u64::from),
657            0x1a => self.read_array().map(u32::from_be_bytes).map(u64::from),
658            0x1b => self.read_array().map(u64::from_be_bytes),
659            _    => Err(Error::type_mismatch(self.type_of(b)?)
660                .with_message("expected u64")
661                .at(p))
662        }
663    }
664
665    /// Get the byte at the current position.
666    fn current(&self) -> Result<u8, Error> {
667        if let Some(b) = self.buf.get(self.pos) {
668            return Ok(*b)
669        }
670        Err(Error::end_of_input())
671    }
672
673    /// Consume and return the byte at the current position.
674    fn read(&mut self) -> Result<u8, Error> {
675        if let Some(b) = self.buf.get(self.pos) {
676            self.pos += 1;
677            return Ok(*b)
678        }
679        Err(Error::end_of_input())
680    }
681
682    /// Peek to the next byte.
683    fn peek(&self) -> Result<u8, Error> {
684        self.pos.checked_add(1)
685            .and_then(|i| self.buf.get(i).copied())
686            .ok_or_else(Error::end_of_input)
687    }
688
689    /// Consume and return *n* bytes starting at the current position.
690    fn read_slice(&mut self, n: usize) -> Result<&'b [u8], Error> {
691        if let Some(b) = self.pos.checked_add(n).and_then(|end| self.buf.get(self.pos .. end)) {
692            self.pos += n;
693            return Ok(b)
694        }
695        Err(Error::end_of_input())
696    }
697
698    /// Consume and return *N* bytes starting at the current position.
699    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error> {
700        self.read_slice(N).map(|slice| {
701            let mut a = [0; N];
702            a.copy_from_slice(slice);
703            a
704        })
705    }
706
707    /// Map the given byte to a [`Type`].
708    fn type_of(&self, n: u8) -> Result<Type, Error> {
709        Ok(match n {
710            0x00 ..= 0x18        => Type::U8,
711            0x19                 => Type::U16,
712            0x1a                 => Type::U32,
713            0x1b                 => Type::U64,
714            0x20 ..= 0x37        => Type::I8,
715            0x38                 => if self.peek()? < 0x80 { Type::I8  } else { Type::I16 }
716            0x39                 => if self.peek()? < 0x80 { Type::I16 } else { Type::I32 }
717            0x3a                 => if self.peek()? < 0x80 { Type::I32 } else { Type::I64 }
718            0x3b                 => if self.peek()? < 0x80 { Type::I64 } else { Type::Int }
719            0x40 ..= 0x5b        => Type::Bytes,
720            0x5f                 => Type::BytesIndef,
721            0x60 ..= 0x7b        => Type::String,
722            0x7f                 => Type::StringIndef,
723            0x80 ..= 0x9b        => Type::Array,
724            0x9f                 => Type::ArrayIndef,
725            0xa0 ..= 0xbb        => Type::Map,
726            0xbf                 => Type::MapIndef,
727            0xc0 ..= 0xdb        => Type::Tag,
728            0xe0 ..= 0xf3 | 0xf8 => Type::Simple,
729            0xf4 | 0xf5          => Type::Bool,
730            0xf6                 => Type::Null,
731            0xf7                 => Type::Undefined,
732            0xf9                 => Type::F16,
733            0xfa                 => Type::F32,
734            0xfb                 => Type::F64,
735            0xff                 => Type::Break,
736            n                    => Type::Unknown(n)
737        })
738    }
739}
740
741/// An iterator over byte slices.
742///
743/// Returned from [`Decoder::bytes_iter`].
744#[derive(Debug)]
745pub struct BytesIter<'a, 'b> {
746    decoder: &'a mut Decoder<'b>,
747    state: State<usize>
748}
749
750impl<'a, 'b> Iterator for BytesIter<'a, 'b> {
751    type Item = Result<&'b [u8], Error>;
752
753    fn next(&mut self) -> Option<Self::Item> {
754        match self.state {
755            State::Indef => match self.decoder.current() {
756                Ok(BREAK) => {
757                    self.state = State::End;
758                    self.decoder.read().map(|_| None).transpose()
759                }
760                Ok(_)  => Some(self.decoder.bytes()),
761                Err(e) => Some(Err(e))
762            }
763            State::End    => None,
764            State::Def(n) => {
765                self.state = State::End;
766                Some(self.decoder.read_slice(n))
767            }
768        }
769    }
770
771    fn size_hint(&self) -> (usize, Option<usize>) {
772        match self.state {
773            State::Def(_) => (1, Some(1)),
774            State::End    => (0, Some(0)),
775            State::Indef  => (0, None)
776        }
777    }
778}
779
780/// An iterator over string slices.
781///
782/// Returned from [`Decoder::str_iter`].
783#[derive(Debug)]
784pub struct StrIter<'a, 'b> {
785    decoder: &'a mut Decoder<'b>,
786    state: State<usize>,
787    pos: usize
788}
789
790impl<'a, 'b> Iterator for StrIter<'a, 'b> {
791    type Item = Result<&'b str, Error>;
792
793    fn next(&mut self) -> Option<Self::Item> {
794        match self.state {
795            State::Indef => match self.decoder.current() {
796                Ok(BREAK) => {
797                    self.state = State::End;
798                    self.decoder.read().map(|_| None).transpose()
799                }
800                Ok(_)  => Some(self.decoder.str()),
801                Err(e) => Some(Err(e))
802            }
803            State::End    => None,
804            State::Def(n) => {
805                self.state = State::End;
806                Some(self.decoder.read_slice(n).and_then(|d| {
807                    str::from_utf8(d).map_err(|e| Error::utf8(e).at(self.pos))
808                }))
809            }
810        }
811    }
812
813    fn size_hint(&self) -> (usize, Option<usize>) {
814        match self.state {
815            State::Def(_) => (1, Some(1)),
816            State::End    => (0, Some(0)),
817            State::Indef  => (0, None)
818        }
819    }
820}
821
822/// An iterator over array elements.
823///
824/// Returned from [`Decoder::array_iter`].
825#[derive(Debug)]
826pub struct ArrayIter<'a, 'b, T> {
827    decoder: &'a mut Decoder<'b>,
828    state: State<u64>,
829    _mark: marker::PhantomData<fn(T)>
830}
831
832impl<'a, 'b, T: Decode<'b, ()>> Iterator for ArrayIter<'a, 'b, T> {
833    type Item = Result<T, Error>;
834
835    fn next(&mut self) -> Option<Self::Item> {
836        match self.state {
837            State::Indef => match self.decoder.current() {
838                Ok(BREAK) => {
839                    self.state = State::End;
840                    self.decoder.read().map(|_| None).transpose()
841                }
842                Ok(_)  => Some(T::decode(self.decoder, &mut ())),
843                Err(e) => Some(Err(e))
844            }
845            State::Def(0) | State::End => None,
846            State::Def(n) => {
847                self.state = State::Def(n - 1);
848                Some(T::decode(self.decoder, &mut ()))
849            }
850        }
851    }
852
853    fn size_hint(&self) -> (usize, Option<usize>) {
854        self.state.into_size_hint()
855    }
856}
857
858/// An iterator over array elements.
859///
860/// Returned from [`Decoder::array_iter_with`].
861#[derive(Debug)]
862pub struct ArrayIterWithCtx<'a, 'b, C, T> {
863    decoder: &'a mut Decoder<'b>,
864    ctx: &'a mut C,
865    state: State<u64>,
866    _mark: marker::PhantomData<fn(T)>
867}
868
869impl<'a, 'b, C, T: Decode<'b, C>> Iterator for ArrayIterWithCtx<'a, 'b, C, T> {
870    type Item = Result<T, Error>;
871
872    fn next(&mut self) -> Option<Self::Item> {
873        match self.state {
874            State::Indef => match self.decoder.current() {
875                Ok(BREAK) => {
876                    self.state = State::End;
877                    self.decoder.read().map(|_| None).transpose()
878                }
879                Ok(_)  => Some(T::decode(self.decoder, self.ctx)),
880                Err(e) => Some(Err(e))
881            }
882            State::Def(0) | State::End => None,
883            State::Def(n) => {
884                self.state = State::Def(n - 1);
885                Some(T::decode(self.decoder, self.ctx))
886            }
887        }
888    }
889
890    fn size_hint(&self) -> (usize, Option<usize>) {
891        self.state.into_size_hint()
892    }
893}
894
895/// An iterator over map entries.
896///
897/// Returned from [`Decoder::map_iter`].
898#[derive(Debug)]
899pub struct MapIter<'a, 'b, K, V> {
900    decoder: &'a mut Decoder<'b>,
901    state: State<u64>,
902    _mark: marker::PhantomData<fn(K, V)>
903}
904
905impl<'a, 'b, K, V> Iterator for MapIter<'a, 'b, K, V>
906where
907    K: Decode<'b, ()>,
908    V: Decode<'b, ()>
909{
910    type Item = Result<(K, V), Error>;
911
912    fn next(&mut self) -> Option<Self::Item> {
913        fn pair<'b, K, V>(d: &mut Decoder<'b>) -> Result<(K, V), Error>
914        where
915            K: Decode<'b, ()>,
916            V: Decode<'b, ()>
917        {
918            Ok((K::decode(d, &mut ())?, V::decode(d, &mut ())?))
919        }
920        match self.state {
921            State::Indef => match self.decoder.current() {
922                Ok(BREAK) => {
923                    self.state = State::End;
924                    self.decoder.read().map(|_| None).transpose()
925                }
926                Ok(_)  => Some(pair(self.decoder)),
927                Err(e) => Some(Err(e))
928            }
929            State::Def(0) | State::End => None,
930            State::Def(n) => {
931                self.state = State::Def(n - 1);
932                Some(pair(self.decoder))
933            }
934        }
935    }
936
937    fn size_hint(&self) -> (usize, Option<usize>) {
938        self.state.into_size_hint()
939    }
940}
941
942/// An iterator over map entries.
943///
944/// Returned from [`Decoder::map_iter_with`].
945#[derive(Debug)]
946pub struct MapIterWithCtx<'a, 'b, C, K, V> {
947    decoder: &'a mut Decoder<'b>,
948    ctx: &'a mut C,
949    state: State<u64>,
950    _mark: marker::PhantomData<fn(K, V)>
951}
952
953impl<'a, 'b, C, K, V> Iterator for MapIterWithCtx<'a, 'b, C, K, V>
954where
955    K: Decode<'b, C>,
956    V: Decode<'b, C>
957{
958    type Item = Result<(K, V), Error>;
959
960    fn next(&mut self) -> Option<Self::Item> {
961        fn pair<'b, C, K, V>(d: &mut Decoder<'b>, ctx: &mut C) -> Result<(K, V), Error>
962        where
963            K: Decode<'b, C>,
964            V: Decode<'b, C>
965        {
966            Ok((K::decode(d, ctx)?, V::decode(d, ctx)?))
967        }
968        match self.state {
969            State::Indef => match self.decoder.current() {
970                Ok(BREAK) => {
971                    self.state = State::End;
972                    self.decoder.read().map(|_| None).transpose()
973                }
974                Ok(_)  => Some(pair(self.decoder, self.ctx)),
975                Err(e) => Some(Err(e))
976            }
977            State::Def(0) | State::End => None,
978            State::Def(n) => {
979                self.state = State::Def(n - 1);
980                Some(pair(self.decoder, self.ctx))
981            }
982        }
983    }
984
985    fn size_hint(&self) -> (usize, Option<usize>) {
986        self.state.into_size_hint()
987    }
988}
989
990/// Iterator state.
991#[derive(Debug, Copy, Clone)]
992enum State<T> {
993    /// Definite length.
994    Def(T),
995    /// End of iteration.
996    End,
997    /// Indefinite length.
998    Indef
999}
1000
1001impl<T> From<Option<T>> for State<T> {
1002    fn from(val: Option<T>) -> Self {
1003        if let Some(n) = val {
1004            Self::Def(n)
1005        } else {
1006            Self::Indef
1007        }
1008    }
1009}
1010
1011impl<T> State<T>
1012where
1013    usize: TryFrom<T>
1014{
1015    fn into_size_hint(self) -> (usize, Option<usize>) {
1016        match self {
1017            Self::Def(n) =>
1018                usize::try_from(n)
1019                    .ok()
1020                    .map(|n| (n, Some(n)))
1021                    .unwrap_or_default(),
1022            Self::End   => (0, Some(0)),
1023            Self::Indef => (0, None)
1024        }
1025    }
1026}
1027
1028/// A decoding probe to to look ahead what comes next.
1029///
1030/// A `Probe` derefs to [`Decoder`] and thus can be used like one without
1031/// affecting the decoder from which it was created.
1032//
1033// The current implementation just clones `Decoder` as it is very cheap
1034// to do so. `Probe` is nevertheless introduced to discourage use of
1035// `Decoder::clone` in client code for this purpose so that it stays
1036// independent of the current implementation.
1037// With a more heavyweight `Decoder`, `Probe` could only store a reference
1038// and the current position which it restores in a `Drop` impl.
1039#[derive(Debug)]
1040pub struct Probe<'a, 'b> {
1041    decoder: Decoder<'b>,
1042    _marker: marker::PhantomData<&'a mut ()>
1043}
1044
1045impl<'b> core::ops::Deref for Probe<'_, 'b> {
1046    type Target = Decoder<'b>;
1047
1048    fn deref(&self) -> &Self::Target {
1049        &self.decoder
1050    }
1051}
1052
1053impl<'b> core::ops::DerefMut for Probe<'_, 'b> {
1054    fn deref_mut(&mut self) -> &mut Self::Target {
1055        &mut self.decoder
1056    }
1057}
1058
1059/// Get the major type info of the given byte (highest 3 bits).
1060pub(crate) fn type_of(b: u8) -> u8 {
1061    b & 0b111_00000
1062}
1063
1064/// Get the additionl type info of the given byte (lowest 5 bits).
1065pub(crate) fn info_of(b: u8) -> u8 {
1066    b & 0b000_11111
1067}
1068
1069fn u64_to_usize(n: u64, pos: usize) -> Result<usize, Error> {
1070    n.try_into().map_err(|_| Error::overflow(n).at(pos).with_message("when converting u64 to usize"))
1071}
1072
1073fn try_as<A, B>(val: A, msg: &'static str, pos: usize) -> Result<B, Error>
1074where
1075    A: TryInto<B> + Into<u64> + Copy
1076{
1077    val.try_into().map_err(|_| Error::overflow(val.into()).at(pos).with_message(msg))
1078}