tinycbor/
lib.rs

1//! A minimal CBOR implementation.
2//!
3//! This was designed from scratch, but is inspired by [`minicbor`][minicbor].
4//!
5//! # Overview
6//!
7//! This crate is organised around the following traits:
8//! - [`Decode`]: Decode types from CBOR. This is equivalent to `Deserialize` in
9//!   [`serde`][serde].
10//! - [`Encode`]: Encode types to CBOR. This is equivalent to `Serialize` in
11//!   [`serde`][serde].
12//! - [`CborLen`]: Calculate the length of a type's CBOR encoding without encoding it.
13//!
14//! One can derive these traits on a type using [`tinycbor-derive`], or implement them manually.
15//!
16//! [minicbor]: https://docs.rs/minicbor
17//! [serde]: https://serde.rs
18//! [`tinycbor-derive`]: https://docs.rs/tinycbor-derive
19//!
20//! # Feature flags
21//!
22//! - `alloc`: Enables support for types in the `alloc` crate, such as `Vec`, `Box`, `Cow`, etc.
23//! - `std`: Implies `alloc`, and adds implementations for types and collections only available
24//!   in the standard library.
25//!
26//! # Example
27//!
28//! A simple encoding and decoding round-trip:
29//! ```
30//! use tinycbor::{Encode, Decode, Encoder, Decoder};
31//!
32//! let input = ["hello", "world"];
33//! let mut buffer = [0u8; 128];
34//! input.encode(&mut Encoder(buffer.as_mut()))?;
35//!
36//! let output: [&str; 2] = Decode::decode(&mut Decoder(&buffer))?;
37//! assert_eq!(input, output);
38//!
39//! # Ok::<_, Box<dyn core::error::Error>>(())
40//! ```
41#![doc = "# Design Axioms\n\n- Simplicity.\n\nThis means reducing the number of lines of code at the cost of functionality.\n\n- Correctness.\n\nIf it is possible to design a simple abstraction that enforces correct usage patterns at compile\ntime, we prefer that. Compared to `minicbor`, the `Encoder` and `Decoder` types\ntry to minimize the number of methods that can lead to invalid CBOR encodings or decoding errors.\nFor example, the `Decoder` exposes `array_visitor`, which allows iterating over the contents of\nand array. Note that correctness is not enforced when the required solution is too complex.\nFor example, `ArrayVisitor` does not ensure that the decoder is in a consistent state if the\n`ArrayVisitor` is dropped before reaching the end of the array. `Encoder` also exposes methods\nto encode the header of an array, without enforcing that the correct number of elements are\nencoded.\n\n- Infallible encoding.\n\nThe `Encode` trait does not support returning encoding errors. The only errors returned are those\ngenerated by the underlying `W: Write`.\n\n- User defined decoding errors.\n\nThe `Decode` trait has an associated `Error` type, allowing for better user-defined error types.\nWhen deriving `Decode`, an error type is also generated.\n\n- Strict decoding.\n\nCompared to `ciborium` and `minicbor`, which follow the\n[\"robustness principle\"](https://en.wikipedia.org/wiki/Robustness_principle), this library is\nstricter in what it accepts when impelenting `Decode` with the derive macro. By default,\narrays containing extra elements are rejected, and default values are not used when a field is\nmissing.\n\n- Use smallest numeric representation when encoding.\n\nIntegers and floats are encoded using the smallest possible representation that does not lose\nprecision. For example, `16u64` is encoded as a `u8`, and `1.0f32` is encoded as a `f16`.\n"include_str!("../DESIGN.md")]
42#![cfg_attr(not(any(feature = "std", test)), no_std)]
43
44// To support targets with 128 bit pointers, we would need to handle collections having lengths
45// larger than supported by the CBOR format. We don't want to deal with that right now.
46#[cfg(not(any(
47    target_pointer_width = "16",
48    target_pointer_width = "32",
49    target_pointer_width = "64"
50)))]
51compile_error!("only targets with 16, 32 or 64 bit pointer width are supported");
52
53#[cfg(feature = "alloc")]
54extern crate alloc;
55
56pub use embedded_io::Write;
57
58mod bytes;
59pub mod collections;
60pub mod num;
61pub mod primitive;
62pub mod string;
63pub mod tag;
64mod wrapper;
65
66const UNSIGNED: u8 = 0x00;
67const SIGNED: u8 = 0x20;
68const BYTES: u8 = 0x40;
69const TEXT: u8 = 0x60;
70const ARRAY: u8 = 0x80;
71const MAP: u8 = 0xa0;
72const TAGGED: u8 = 0xc0;
73const SIMPLE: u8 = 0xe0;
74const BREAK: u8 = 0xff;
75
76/// Encode a type implementing [`Encode`] and return the encoded byte vector.
77///
78/// *Requires feature* `"alloc"`.
79#[cfg(feature = "alloc")]
80pub fn to_vec<T>(x: &T) -> alloc::vec::Vec<u8>
81where
82    T: Encode,
83{
84    let mut buf = alloc::vec::Vec::new();
85    let Ok(()) = x.encode(&mut Encoder(&mut buf));
86    buf
87}
88
89/// Error indicating that the end of input has been reached.
90#[derive(#[automatically_derived]
impl ::core::fmt::Debug for EndOfInput {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "EndOfInput")
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for EndOfInput {
    #[inline]
    fn clone(&self) -> EndOfInput { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EndOfInput { }Copy, #[automatically_derived]
impl ::core::default::Default for EndOfInput {
    #[inline]
    fn default() -> EndOfInput { EndOfInput {} }
}Default, #[automatically_derived]
impl ::core::cmp::PartialEq for EndOfInput {
    #[inline]
    fn eq(&self, other: &EndOfInput) -> bool { true }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for EndOfInput {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for EndOfInput {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {}
}Hash)]
91pub struct EndOfInput;
92
93impl core::fmt::Display for EndOfInput {
94    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
95        f.write_fmt(format_args!("end of input"))write!(f, "end of input")
96    }
97}
98
99impl core::error::Error for EndOfInput {}
100
101/// Error indicating that the CBOR header (first byte) is invalid or malformed.
102///
103/// This can happen if the header byte represents a different type than expected, or if the header
104/// byte is malformed (e.g., uses a reserved value from the CBOR specification).
105#[derive(#[automatically_derived]
impl ::core::fmt::Debug for InvalidHeader {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "InvalidHeader")
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for InvalidHeader {
    #[inline]
    fn clone(&self) -> InvalidHeader { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for InvalidHeader { }Copy, #[automatically_derived]
impl ::core::default::Default for InvalidHeader {
    #[inline]
    fn default() -> InvalidHeader { InvalidHeader {} }
}Default, #[automatically_derived]
impl ::core::cmp::PartialEq for InvalidHeader {
    #[inline]
    fn eq(&self, other: &InvalidHeader) -> bool { true }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for InvalidHeader {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for InvalidHeader {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {}
}Hash)]
106pub struct InvalidHeader;
107
108impl core::fmt::Display for InvalidHeader {
109    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
110        f.write_fmt(format_args!("invalid header"))write!(f, "invalid header")
111    }
112}
113
114impl core::error::Error for InvalidHeader {}
115
116/// A non-allocating CBOR encoder writing encoded bytes to the given [`Write`] sink.
117#[derive(#[automatically_derived]
impl<W: ::core::fmt::Debug> ::core::fmt::Debug for Encoder<W> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Encoder",
            &&self.0)
    }
}Debug, #[automatically_derived]
impl<W: ::core::default::Default> ::core::default::Default for Encoder<W> {
    #[inline]
    fn default() -> Encoder<W> {
        Encoder(::core::default::Default::default())
    }
}Default, #[automatically_derived]
impl<W: ::core::clone::Clone> ::core::clone::Clone for Encoder<W> {
    #[inline]
    fn clone(&self) -> Encoder<W> {
        Encoder(::core::clone::Clone::clone(&self.0))
    }
}Clone, #[automatically_derived]
impl<W: ::core::marker::Copy> ::core::marker::Copy for Encoder<W> { }Copy, #[automatically_derived]
impl<W: ::core::cmp::PartialEq> ::core::cmp::PartialEq for Encoder<W> {
    #[inline]
    fn eq(&self, other: &Encoder<W>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<W: ::core::cmp::Eq> ::core::cmp::Eq for Encoder<W> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<W>;
    }
}Eq, #[automatically_derived]
impl<W: ::core::cmp::PartialOrd> ::core::cmp::PartialOrd for Encoder<W> {
    #[inline]
    fn partial_cmp(&self, other: &Encoder<W>)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::cmp::PartialOrd::partial_cmp(&self.0, &other.0)
    }
}PartialOrd, #[automatically_derived]
impl<W: ::core::cmp::Ord> ::core::cmp::Ord for Encoder<W> {
    #[inline]
    fn cmp(&self, other: &Encoder<W>) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.0, &other.0)
    }
}Ord, #[automatically_derived]
impl<W: ::core::hash::Hash> ::core::hash::Hash for Encoder<W> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
118pub struct Encoder<W>(pub W);
119
120impl<W: Write> Encoder<W> {
121    /// Begin encoding an array with `len` elements.
122    pub fn array(&mut self, len: usize) -> Result<(), W::Error> {
123        self.type_len(ARRAY, len as u64)
124    }
125
126    /// Begin encoding an array of unknown size.
127    ///
128    /// Use [`Encoder::end`] to terminate the array.
129    pub fn begin_array(&mut self) -> Result<(), W::Error> {
130        self.put(&[0x9f])
131    }
132
133    /// Begin encoding a map with `len` entries.
134    pub fn map(&mut self, len: usize) -> Result<(), W::Error> {
135        self.type_len(MAP, len as u64)
136    }
137
138    /// Begin encoding a map of unknown size.
139    ///
140    /// Use [`Encoder::end`] to terminate the map.
141    pub fn begin_map(&mut self) -> Result<(), W::Error> {
142        self.put(&[0xbf])
143    }
144
145    // TODO: struct that prevents wrong use
146    /// Begin encoding an indefinite number of byte slices.
147    ///
148    /// Use [`Encoder::end`] to terminate.
149    pub fn begin_bytes(&mut self) -> Result<(), W::Error> {
150        self.put(&[0x5f])
151    }
152
153    // TODO: struct that prevents wrong use
154    /// Begin encoding an indefinite number of string slices.
155    ///
156    /// Use [`Encoder::end`] to terminate.
157    pub fn begin_str(&mut self) -> Result<(), W::Error> {
158        self.put(&[0x7f])
159    }
160
161    /// Terminate an indefinite collection.
162    pub fn end(&mut self) -> Result<(), W::Error> {
163        self.put(&[0xff])
164    }
165
166    /// Write the encoded byte slice.
167    fn put(&mut self, b: &[u8]) -> Result<(), W::Error> {
168        self.0.write_all(b)
169    }
170
171    /// Write type and length information.
172    fn type_len(&mut self, t: u8, x: u64) -> Result<(), W::Error> {
173        match x {
174            0..=0x17 => self.put(&[t | x as u8]),
175            0x18..=0xff => self.put(&[t | 24, x as u8]),
176            0x100..=0xffff => {
177                self.put(&[t | 25])?;
178                self.put(&(x as u16).to_be_bytes()[..])
179            }
180            0x1_0000..=0xffff_ffff => {
181                self.put(&[t | 26])?;
182                self.put(&(x as u32).to_be_bytes())
183            }
184            _ => {
185                self.put(&[t | 27])?;
186                self.put(&x.to_be_bytes()[..])
187            }
188        }
189    }
190}
191
192/// A CBOR decoder.
193///
194/// Decodes the content of the byte slice.
195#[derive(#[automatically_derived]
impl<'b> ::core::fmt::Debug for Decoder<'b> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Decoder",
            &&self.0)
    }
}Debug, #[automatically_derived]
impl<'b> ::core::clone::Clone for Decoder<'b> {
    #[inline]
    fn clone(&self) -> Decoder<'b> {
        let _: ::core::clone::AssertParamIsClone<&'b [u8]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'b> ::core::marker::Copy for Decoder<'b> { }Copy, #[automatically_derived]
impl<'b> ::core::cmp::PartialEq for Decoder<'b> {
    #[inline]
    fn eq(&self, other: &Decoder<'b>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'b> ::core::cmp::Eq for Decoder<'b> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<&'b [u8]>;
    }
}Eq, #[automatically_derived]
impl<'b> ::core::hash::Hash for Decoder<'b> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
196pub struct Decoder<'b>(pub &'b [u8]);
197
198impl<'b> Decoder<'b> {
199    /// Decode a definite or indefinite bytestring.
200    ///
201    /// Returns an iterator the potentially many (if indefinite) byte slices that make up the
202    /// bytestring.
203    pub fn bytes_iter(&mut self) -> Result<BytesIter<'_, 'b>, primitive::Error> {
204        let b = self.peek().map_err(primitive::Error::EndOfInput)?;
205        if BYTES != type_of(b) {
206            return Err(primitive::Error::InvalidHeader(InvalidHeader));
207        }
208        let state = if info_of(b) == 31 {
209            self.read().expect("was peeked");
210            if self.peek() == Ok(BREAK) {
211                self.read().expect("was peeked");
212                State::Indef(true)
213            } else {
214                State::Indef(false)
215            }
216        } else {
217            let n = self.length()?;
218            State::Def(n)
219        };
220
221        Ok(BytesIter {
222            decoder: self,
223            state,
224        })
225    }
226
227    /// Decode a definite or indefinite UTF-8 string.
228    ///
229    /// Returns an iterator the potentially many (if indefinite) string slices that make up the
230    /// UTF-8 string.
231    pub fn str_iter(&mut self) -> Result<StrIter<'_, 'b>, primitive::Error> {
232        let b = self.peek().map_err(primitive::Error::EndOfInput)?;
233        if TEXT != type_of(b) {
234            return Err(primitive::Error::InvalidHeader(InvalidHeader));
235        }
236        let state = if info_of(b) == 31 {
237            self.read().expect("was peeked");
238            if self.peek() == Ok(BREAK) {
239                self.read().expect("was peeked");
240                State::Indef(true)
241            } else {
242                State::Indef(false)
243            }
244        } else {
245            let n = self.length()?;
246            State::Def(n)
247        };
248
249        Ok(StrIter {
250            decoder: self,
251            state,
252        })
253    }
254
255    /// Begin decoding an array with a visitor.
256    ///
257    /// The [`ArrayVisitor`] allows iterating over the elements of different types with the
258    /// [`ArrayVisitor::visit`] method.
259    pub fn array_visitor(&mut self) -> Result<ArrayVisitor<'_, 'b>, primitive::Error> {
260        let b = self.peek()?;
261        if ARRAY != type_of(b) {
262            return Err(primitive::Error::InvalidHeader(InvalidHeader));
263        }
264        let state = if info_of(b) == 31 {
265            self.read().expect("was peeked");
266            if self.peek() == Ok(BREAK) {
267                self.read().expect("was peeked");
268                State::Indef(true)
269            } else {
270                State::Indef(false)
271            }
272        } else {
273            let n = self.length()?;
274            State::Def(n)
275        };
276        Ok(ArrayVisitor {
277            decoder: self,
278            state,
279        })
280    }
281
282    /// Begin decoding a map with a visitor.
283    ///
284    /// The [`MapVisitor`] allows iterating over the key-value pairs of different types with the
285    /// [`MapVisitor::visit`] method.
286    pub fn map_visitor(&mut self) -> Result<MapVisitor<'_, 'b>, primitive::Error> {
287        let b = self.peek().map_err(primitive::Error::from)?;
288        if MAP != type_of(b) {
289            return Err(primitive::Error::InvalidHeader(InvalidHeader));
290        }
291        let state = if info_of(b) == 31 {
292            self.read().expect("was peeked");
293            if self.peek() == Ok(BREAK) {
294                self.read().expect("was peeked");
295                State::Indef(true)
296            } else {
297                State::Indef(false)
298            }
299        } else {
300            let n = self.length()?;
301            State::Def(n)
302        };
303        Ok(MapVisitor {
304            decoder: self,
305            state,
306        })
307    }
308
309    /// Inspect the CBOR type at the current position.
310    pub fn datatype(&self) -> Result<Type, EndOfInput> {
311        Ok(match self.peek()? {
312            UNSIGNED..=0x1b | SIGNED..=0x3b => Type::Int,
313            BYTES..=0x5b => Type::Bytes,
314            0x5f => Type::BytesIndef,
315            TEXT..=0x7b => Type::String,
316            0x7f => Type::StringIndef,
317            ARRAY..=0x9b => Type::Array,
318            0x9f => Type::ArrayIndef,
319            MAP..=0xbb => Type::Map,
320            0xbf => Type::MapIndef,
321            TAGGED..=0xdb => Type::Tag,
322            SIMPLE..=0xf3 | 0xf8 => Type::Simple,
323            0xf4 | 0xf5 => Type::Bool,
324            0xf6 => Type::Null,
325            0xf7 => Type::Undefined,
326            0xf9..=0xfb => Type::Float,
327            BREAK => Type::Break,
328            _ => Type::Unknown,
329        })
330    }
331
332    fn unsigned(&mut self) -> Result<u64, primitive::Error> {
333        Ok(match info_of(self.read()?) {
334            n @ 0..=0x17 => Ok(u64::from(n)),
335            0x18 => self.read().map(u64::from),
336            0x19 => self.read_array().map(u16::from_be_bytes).map(u64::from),
337            0x1a => self.read_array().map(u32::from_be_bytes).map(u64::from),
338            0x1b => self.read_array().map(u64::from_be_bytes),
339            _ => return Err(primitive::Error::InvalidHeader(InvalidHeader)),
340        }?)
341    }
342
343    /// Decode an unsigned length from the decoder. converting from u64 to usize is fine when it is
344    /// a length because lengths larger than usize::MAX cannot be represented in memory anyway.
345    fn length(&mut self) -> Result<usize, primitive::Error> {
346        Ok(self.unsigned()?.try_into().unwrap_or(usize::MAX))
347    }
348
349    /// Consume and return the byte at the current position.
350    fn read(&mut self) -> Result<u8, EndOfInput> {
351        if let Some(b) = self.0.first() {
352            self.0 = &self.0[1..];
353            return Ok(*b);
354        }
355        Err(EndOfInput)
356    }
357
358    /// Peek to the next byte.
359    fn peek(&self) -> Result<u8, EndOfInput> {
360        self.0.first().copied().ok_or(EndOfInput)
361    }
362
363    /// Consume and return *n* bytes starting at the current position.
364    fn read_slice(&mut self, n: usize) -> Result<&'b [u8], EndOfInput> {
365        if let Some(b) = self.0.get(..n) {
366            self.0 = &self.0[n..];
367            return Ok(b);
368        }
369        Err(EndOfInput)
370    }
371
372    /// Consume and return *N* bytes starting at the current position.
373    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], EndOfInput> {
374        self.read_slice(N).map(|slice| {
375            let mut a = [0; N];
376            a.copy_from_slice(slice);
377            a
378        })
379    }
380}
381
382/// Iterate over the [`Token`]s in the decoder.
383///
384/// ```
385/// use tinycbor::{Decoder, Encoder, Token};
386///
387/// let input  = [0x83, 0x01, 0x9f, 0x02, 0x03, 0xff, 0x82, 0x04, 0x05];
388/// let tokens = Decoder(&input);
389/// let expected = &[
390///     Token::Array(3),
391///     Token::Int(From::from(1)),
392///     Token::BeginArray,
393///     Token::Int(From::from(2)),
394///     Token::Int(From::from(3)),
395///     Token::Break,
396///     Token::Array(2),
397///     Token::Int(From::from(4)),
398///     Token::Int(From::from(5))
399/// ];
400///
401/// for (token, expected) in tokens.zip(expected.iter()) {
402///     assert_eq!(&token?, expected);
403/// }
404/// # Ok::<_, Box<dyn core::error::Error>>(())
405/// ```
406impl<'b> Iterator for Decoder<'b> {
407    type Item = Result<Token<'b>, string::Error>;
408
409    fn next(&mut self) -> Option<Self::Item> {
410        if self.0.is_empty() {
411            return None;
412        }
413        Some(Token::decode(self))
414    }
415}
416
417/// Display the CBOR data items left in the decoder.
418///
419/// ```
420/// use tinycbor::Decoder;
421///
422/// let input  = [0x83, 0x01, 0x9f, 0x02, 0x03, 0xff, 0x82, 0x04, 0x05];
423///
424/// assert_eq!("[1, [_ 2, 3], [4, 5]]", format!("{}", Decoder(&input)));
425/// ```
426///
427#[cfg(feature = "alloc")]
428impl core::fmt::Display for Decoder<'_> {
429    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
430        /// Control stack element.
431        enum E {
432            N(bool),          // get next token (true => token is required)
433            T,                // tag
434            A(Option<usize>), // array
435            M(Option<usize>), // map
436            B,                // indefinite bytes
437            D,                // indefinite text
438            S(&'static str),  // display string
439            X(&'static str),  // display string (unless next token is BREAK)
440        }
441
442        let mut iter = self.peekable();
443        let mut stack = alloc::vec::Vec::new();
444
445        while iter.peek().is_some() {
446            stack.push(E::N(false));
447            while let Some(elt) = stack.pop() {
448                match elt {
449                    E::N(required) => match iter.next() {
450                        Some(Ok(Token::Array(n))) => {
451                            stack.push(E::A(Some(n)));
452                            f.write_str("[")?
453                        }
454                        Some(Ok(Token::Map(n))) => {
455                            stack.push(E::M(Some(n)));
456                            f.write_str("{")?
457                        }
458                        Some(Ok(Token::BeginArray)) => {
459                            stack.push(E::A(None));
460                            f.write_str("[_ ")?
461                        }
462                        Some(Ok(Token::BeginMap)) => {
463                            stack.push(E::M(None));
464                            f.write_str("{_ ")?
465                        }
466                        Some(Ok(Token::BeginBytes)) => {
467                            if let Some(Ok(Token::Break)) = iter.peek() {
468                                iter.next();
469                                f.write_str("''_")?
470                            } else {
471                                stack.push(E::B);
472                                f.write_str("(_ ")?
473                            }
474                        }
475                        Some(Ok(Token::BeginString)) => {
476                            if let Some(Ok(Token::Break)) = iter.peek() {
477                                iter.next();
478                                f.write_str("\"\"_")?
479                            } else {
480                                stack.push(E::D);
481                                f.write_str("(_ ")?
482                            }
483                        }
484                        Some(Ok(Token::Tag(t))) => {
485                            stack.push(E::T);
486                            f.write_fmt(format_args!("{0}(", t))write!(f, "{}(", t)?
487                        }
488                        Some(Ok(t)) => t.fmt(f)?,
489                        Some(Err(e)) => {
490                            f.write_fmt(format_args!(" !!! decoding error: {0}", e))write!(f, " !!! decoding error: {e}")?;
491                            return Ok(());
492                        }
493                        None => {
494                            if required {
495                                f.write_str(" !!! decoding error: unexpected end of input")?;
496                                return Ok(());
497                            } else {
498                                continue;
499                            }
500                        }
501                    },
502                    E::S(s) => f.write_str(s)?,
503                    E::X(s) => match iter.peek() {
504                        Some(Ok(Token::Break)) | None => continue,
505                        Some(Ok(_)) => f.write_str(s)?,
506                        Some(Err(e)) => {
507                            f.write_fmt(format_args!(" !!! decoding error: {0}", e))write!(f, " !!! decoding error: {e}")?;
508                            return Ok(());
509                        }
510                    },
511                    E::T => {
512                        stack.push(E::S(")"));
513                        stack.push(E::N(true))
514                    }
515                    E::A(Some(0)) => f.write_str("]")?,
516                    E::A(Some(1)) => {
517                        stack.push(E::A(Some(0)));
518                        stack.push(E::N(true))
519                    }
520                    E::A(Some(n)) => {
521                        stack.push(E::A(Some(n - 1)));
522                        stack.push(E::S(", "));
523                        stack.push(E::N(true))
524                    }
525                    E::A(None) => match iter.peek() {
526                        None => {
527                            f.write_str(" !!! indefinite array not closed")?;
528                            return Ok(());
529                        }
530                        Some(Ok(Token::Break)) => {
531                            iter.next();
532                            f.write_str("]")?
533                        }
534                        _ => {
535                            stack.push(E::A(None));
536                            stack.push(E::X(", "));
537                            stack.push(E::N(true))
538                        }
539                    },
540                    E::M(Some(0)) => f.write_str("}")?,
541                    E::M(Some(1)) => {
542                        stack.push(E::M(Some(0)));
543                        stack.push(E::N(true));
544                        stack.push(E::S(": "));
545                        stack.push(E::N(true))
546                    }
547                    E::M(Some(n)) => {
548                        stack.push(E::M(Some(n - 1)));
549                        stack.push(E::S(", "));
550                        stack.push(E::N(true));
551                        stack.push(E::S(": "));
552                        stack.push(E::N(true))
553                    }
554                    E::M(None) => match iter.peek() {
555                        None => {
556                            f.write_str(" !!! indefinite map not closed")?;
557                            return Ok(());
558                        }
559                        Some(Ok(Token::Break)) => {
560                            iter.next();
561                            f.write_str("}")?
562                        }
563                        _ => {
564                            stack.push(E::M(None));
565                            stack.push(E::X(", "));
566                            stack.push(E::N(true));
567                            stack.push(E::S(": "));
568                            stack.push(E::N(true))
569                        }
570                    },
571                    E::B => match iter.peek() {
572                        None => {
573                            f.write_str(" !!! indefinite byte string not closed")?;
574                            return Ok(());
575                        }
576                        Some(Ok(Token::Break)) => {
577                            iter.next();
578                            f.write_str(")")?
579                        }
580                        _ => {
581                            stack.push(E::B);
582                            stack.push(E::X(", "));
583                            stack.push(E::N(true))
584                        }
585                    },
586                    E::D => match iter.peek() {
587                        None => {
588                            f.write_str(" !!! indefinite string not closed")?;
589                            return Ok(());
590                        }
591                        Some(Ok(Token::Break)) => {
592                            iter.next();
593                            f.write_str(")")?
594                        }
595                        _ => {
596                            stack.push(E::D);
597                            stack.push(E::X(", "));
598                            stack.push(E::N(true))
599                        }
600                    },
601                }
602            }
603        }
604
605        Ok(())
606    }
607}
608
609/// A type that can be encoded to CBOR.
610pub trait Encode {
611    /// Encode a value of this type using the given `Writer`.
612    fn encode<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), W::Error>;
613}
614
615/// A type that can calculate its own CBOR encoding length.
616pub trait CborLen {
617    /// Compute the CBOR encoding length in bytes of this value.
618    fn cbor_len(&self) -> usize;
619}
620
621/// A type that can be decoded from CBOR.
622pub trait Decode<'b>: Sized {
623    /// The error type returned when decoding fails.
624    type Error: core::error::Error + 'static;
625
626    /// Decode a value using the given `Decoder`.
627    fn decode(d: &mut Decoder<'b>) -> Result<Self, Self::Error>;
628}
629
630/// Get the major type info of the given byte (highest 3 bits).
631fn type_of(b: u8) -> u8 {
632    b & 0b111_00000
633}
634
635/// Get the additionl type info of the given byte (lowest 5 bits).
636fn info_of(b: u8) -> u8 {
637    b & 0b000_11111
638}
639
640/// Iterator state.
641#[derive(#[automatically_derived]
impl ::core::fmt::Debug for State {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            State::Def(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Def",
                    &__self_0),
            State::Indef(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Indef",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for State { }Copy, #[automatically_derived]
impl ::core::clone::Clone for State {
    #[inline]
    fn clone(&self) -> State {
        let _: ::core::clone::AssertParamIsClone<usize>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for State {
    #[inline]
    fn eq(&self, other: &State) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (State::Def(__self_0), State::Def(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (State::Indef(__self_0), State::Indef(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for State {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<usize>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for State {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            State::Def(__self_0) => ::core::hash::Hash::hash(__self_0, state),
            State::Indef(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
        }
    }
}Hash)]
642enum State {
643    /// Definite length.
644    Def(usize),
645    /// Indefinite length. Stores whether the end has been reached.
646    Indef(bool),
647}
648
649impl From<Option<usize>> for State {
650    fn from(val: Option<usize>) -> Self {
651        if let Some(n) = val {
652            Self::Def(n)
653        } else {
654            Self::Indef(false)
655        }
656    }
657}
658
659impl State {
660    fn remaining(&self) -> Option<usize> {
661        match self {
662            State::Def(n) => Some(*n),
663            State::Indef(done) => done.then_some(0),
664        }
665    }
666}
667
668/// An iterator over byte slices.
669///
670/// Returned from [`Decoder::bytes_iter`].
671#[derive(#[automatically_derived]
impl<'a, 'b> ::core::fmt::Debug for BytesIter<'a, 'b> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "BytesIter",
            "decoder", &self.decoder, "state", &&self.state)
    }
}Debug, #[automatically_derived]
impl<'a, 'b> ::core::cmp::PartialEq for BytesIter<'a, 'b> {
    #[inline]
    fn eq(&self, other: &BytesIter<'a, 'b>) -> bool {
        self.decoder == other.decoder && self.state == other.state
    }
}PartialEq, #[automatically_derived]
impl<'a, 'b> ::core::cmp::Eq for BytesIter<'a, 'b> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<&'a mut Decoder<'b>>;
        let _: ::core::cmp::AssertParamIsEq<State>;
    }
}Eq, #[automatically_derived]
impl<'a, 'b> ::core::hash::Hash for BytesIter<'a, 'b> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        ::core::hash::Hash::hash(&self.decoder, state);
        ::core::hash::Hash::hash(&self.state, state)
    }
}Hash)]
672pub struct BytesIter<'a, 'b> {
673    decoder: &'a mut Decoder<'b>,
674    state: State,
675}
676
677impl<'b> Iterator for BytesIter<'_, 'b> {
678    type Item = Result<&'b [u8], primitive::Error>;
679
680    fn next(&mut self) -> Option<Self::Item> {
681        match self.state {
682            State::Indef(false) => {
683                let bytes = Decode::decode(self.decoder);
684                if let Ok(BREAK) = self.decoder.peek() {
685                    self.decoder.read().expect("was peeked");
686                    self.state = State::Indef(true);
687                }
688                Some(bytes)
689            }
690            State::Def(0) | State::Indef(true) => None,
691            State::Def(n) => {
692                self.state = State::Def(0);
693                Some(self.decoder.read_slice(n).map_err(primitive::Error::from))
694            }
695        }
696    }
697
698    fn size_hint(&self) -> (usize, Option<usize>) {
699        match self.state {
700            State::Def(_) => (1, Some(1)),
701            State::Indef(true) => (0, Some(0)),
702            State::Indef(false) => (0, None),
703        }
704    }
705}
706
707/// Iterate over string slices.
708///
709/// Returned from [`Decoder::str_iter`].
710#[derive(#[automatically_derived]
impl<'a, 'b> ::core::fmt::Debug for StrIter<'a, 'b> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "StrIter",
            "decoder", &self.decoder, "state", &&self.state)
    }
}Debug, #[automatically_derived]
impl<'a, 'b> ::core::cmp::PartialEq for StrIter<'a, 'b> {
    #[inline]
    fn eq(&self, other: &StrIter<'a, 'b>) -> bool {
        self.decoder == other.decoder && self.state == other.state
    }
}PartialEq, #[automatically_derived]
impl<'a, 'b> ::core::cmp::Eq for StrIter<'a, 'b> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<&'a mut Decoder<'b>>;
        let _: ::core::cmp::AssertParamIsEq<State>;
    }
}Eq, #[automatically_derived]
impl<'a, 'b> ::core::hash::Hash for StrIter<'a, 'b> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        ::core::hash::Hash::hash(&self.decoder, state);
        ::core::hash::Hash::hash(&self.state, state)
    }
}Hash)]
711pub struct StrIter<'a, 'b> {
712    decoder: &'a mut Decoder<'b>,
713    state: State,
714}
715
716impl<'b> Iterator for StrIter<'_, 'b> {
717    type Item = Result<&'b str, string::Error>;
718
719    fn next(&mut self) -> Option<Self::Item> {
720        match self.state {
721            State::Indef(false) => {
722                let s = Decode::decode(self.decoder);
723                if let Ok(BREAK) = self.decoder.peek() {
724                    self.decoder.read().expect("was peeked");
725                    self.state = State::Indef(true);
726                }
727                Some(s)
728            }
729            State::Def(0) | State::Indef(true) => None,
730            State::Def(n) => {
731                self.state = State::Def(0);
732                Some(
733                    self.decoder
734                        .read_slice(n)
735                        .map_err(string::Error::from)
736                        .and_then(|slice| core::str::from_utf8(slice).map_err(string::Error::from)),
737                )
738            }
739        }
740    }
741
742    fn size_hint(&self) -> (usize, Option<usize>) {
743        match self.state {
744            State::Def(_) => (1, Some(1)),
745            State::Indef(true) => (0, Some(0)),
746            State::Indef(false) => (0, None),
747        }
748    }
749}
750
751/// A visitor for decoding array elements of different types.
752///
753/// Returned from [`Decoder::array_visitor`].
754#[derive(#[automatically_derived]
impl<'a, 'b> ::core::fmt::Debug for ArrayVisitor<'a, 'b> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "ArrayVisitor",
            "decoder", &self.decoder, "state", &&self.state)
    }
}Debug, #[automatically_derived]
impl<'a, 'b> ::core::cmp::PartialEq for ArrayVisitor<'a, 'b> {
    #[inline]
    fn eq(&self, other: &ArrayVisitor<'a, 'b>) -> bool {
        self.decoder == other.decoder && self.state == other.state
    }
}PartialEq, #[automatically_derived]
impl<'a, 'b> ::core::cmp::Eq for ArrayVisitor<'a, 'b> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<&'a mut Decoder<'b>>;
        let _: ::core::cmp::AssertParamIsEq<State>;
    }
}Eq, #[automatically_derived]
impl<'a, 'b> ::core::hash::Hash for ArrayVisitor<'a, 'b> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        ::core::hash::Hash::hash(&self.decoder, state);
        ::core::hash::Hash::hash(&self.state, state)
    }
}Hash)]
755pub struct ArrayVisitor<'a, 'b> {
756    decoder: &'a mut Decoder<'b>,
757    state: State,
758}
759
760impl<'b> ArrayVisitor<'_, 'b> {
761    /// Visit the next element in the array.
762    pub fn visit<T: Decode<'b>>(&mut self) -> Option<Result<T, T::Error>> {
763        match self.state {
764            State::Indef(false) => {
765                let value = T::decode(self.decoder);
766                if let Ok(BREAK) = self.decoder.peek() {
767                    self.decoder.read().expect("was peeked");
768                    self.state = State::Indef(true);
769                }
770                Some(value)
771            }
772            State::Indef(true) | State::Def(0) => None,
773            State::Def(n) => {
774                self.state = State::Def(n - 1);
775                Some(T::decode(self.decoder))
776            }
777        }
778    }
779
780    pub fn remaining(&self) -> Option<usize> {
781        self.state.remaining()
782    }
783
784    pub fn definite(&self) -> bool {
785        #[allow(non_exhaustive_omitted_patterns)] match self.state {
    State::Def(_) => true,
    _ => false,
}matches!(self.state, State::Def(_))
786    }
787}
788
789/// A visitor for decoding map key-value pairs of different types.
790///
791/// Returned from [`Decoder::map_visitor`].
792#[derive(#[automatically_derived]
impl<'a, 'b> ::core::fmt::Debug for MapVisitor<'a, 'b> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "MapVisitor",
            "decoder", &self.decoder, "state", &&self.state)
    }
}Debug, #[automatically_derived]
impl<'a, 'b> ::core::cmp::PartialEq for MapVisitor<'a, 'b> {
    #[inline]
    fn eq(&self, other: &MapVisitor<'a, 'b>) -> bool {
        self.decoder == other.decoder && self.state == other.state
    }
}PartialEq, #[automatically_derived]
impl<'a, 'b> ::core::cmp::Eq for MapVisitor<'a, 'b> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<&'a mut Decoder<'b>>;
        let _: ::core::cmp::AssertParamIsEq<State>;
    }
}Eq, #[automatically_derived]
impl<'a, 'b> ::core::hash::Hash for MapVisitor<'a, 'b> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        ::core::hash::Hash::hash(&self.decoder, state);
        ::core::hash::Hash::hash(&self.state, state)
    }
}Hash)]
793pub struct MapVisitor<'a, 'b> {
794    decoder: &'a mut Decoder<'b>,
795    state: State,
796}
797
798impl<'b> MapVisitor<'_, 'b> {
799    /// Visit the next key-value pair in the map.
800    #[allow(clippy::type_complexity)]
801    pub fn visit<K: Decode<'b>, V: Decode<'b>>(
802        &mut self,
803    ) -> Option<Result<(K, V), collections::map::Error<K::Error, V::Error>>> {
804        Some(match self.with_key(|k, d| (k, V::decode(d)))? {
805            Ok((k, Ok(v))) => Ok((k, v)),
806            Ok((_, Err(v))) => Err(collections::map::Error::Value(v)),
807            Err(k) => Err(collections::map::Error::Key(k)),
808        })
809    }
810
811    /// Visit the next key in the map, applying the given function to decode the value.
812    pub fn with_key<K, F, O>(&mut self, f: F) -> Option<Result<O, K::Error>>
813    where
814        K: Decode<'b>,
815        F: FnOnce(K, &mut Decoder<'b>) -> O,
816    {
817        match self.state {
818            State::Indef(false) => {
819                let key = K::decode(self.decoder);
820                if let Ok(BREAK) = self.decoder.peek() {
821                    self.decoder.read().expect("was peeked");
822                    self.state = State::Indef(true);
823                }
824                match key {
825                    Ok(k) => Some(Ok(f(k, self.decoder))),
826                    Err(e) => Some(Err(e)),
827                }
828            }
829            State::Indef(true) | State::Def(0) => None,
830            State::Def(n) => {
831                self.state = State::Def(n - 1);
832                let key = K::decode(self.decoder);
833                match key {
834                    Ok(k) => Some(Ok(f(k, self.decoder))),
835                    Err(e) => Some(Err(e)),
836                }
837            }
838        }
839    }
840
841    pub fn remaining(&self) -> Option<usize> {
842        self.state.remaining()
843    }
844
845    pub fn definite(&self) -> bool {
846        #[allow(non_exhaustive_omitted_patterns)] match self.state {
    State::Def(_) => true,
    _ => false,
}matches!(self.state, State::Def(_))
847    }
848}
849
850/// CBOR data type.
851#[derive(#[automatically_derived]
impl ::core::clone::Clone for Type {
    #[inline]
    fn clone(&self) -> Type { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Type { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for Type {
    #[inline]
    fn eq(&self, other: &Type) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Type {
    #[inline]
    fn partial_cmp(&self, other: &Type)
        -> ::core::option::Option<::core::cmp::Ordering> {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        ::core::cmp::PartialOrd::partial_cmp(&__self_discr, &__arg1_discr)
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Eq for Type {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {}
}Eq, #[automatically_derived]
impl ::core::cmp::Ord for Type {
    #[inline]
    fn cmp(&self, other: &Type) -> ::core::cmp::Ordering {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        ::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr)
    }
}Ord, #[automatically_derived]
impl ::core::fmt::Debug for Type {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Type::Bool => "Bool",
                Type::Null => "Null",
                Type::Undefined => "Undefined",
                Type::Int => "Int",
                Type::Float => "Float",
                Type::Simple => "Simple",
                Type::Bytes => "Bytes",
                Type::BytesIndef => "BytesIndef",
                Type::String => "String",
                Type::StringIndef => "StringIndef",
                Type::Array => "Array",
                Type::ArrayIndef => "ArrayIndef",
                Type::Map => "Map",
                Type::MapIndef => "MapIndef",
                Type::Tag => "Tag",
                Type::Break => "Break",
                Type::Unknown => "Unknown",
            })
    }
}Debug, #[automatically_derived]
impl ::core::hash::Hash for Type {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state)
    }
}Hash)]
852pub enum Type {
853    Bool,
854    Null,
855    Undefined,
856    Int,
857    Float,
858    Simple,
859    Bytes,
860    BytesIndef,
861    String,
862    StringIndef,
863    Array,
864    ArrayIndef,
865    Map,
866    MapIndef,
867    Tag,
868    Break,
869    Unknown,
870}
871
872impl core::fmt::Display for Type {
873    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
874        match self {
875            Type::Bool => f.write_str("bool"),
876            Type::Null => f.write_str("null"),
877            Type::Undefined => f.write_str("undefined"),
878            Type::Int => f.write_str("int"),
879            Type::Float => f.write_str("f64"),
880            Type::Simple => f.write_str("simple"),
881            Type::Bytes => f.write_str("bytes"),
882            Type::BytesIndef => f.write_str("indefinite bytes"),
883            Type::String => f.write_str("string"),
884            Type::StringIndef => f.write_str("indefinite string"),
885            Type::Array => f.write_str("array"),
886            Type::ArrayIndef => f.write_str("indefinite array"),
887            Type::Map => f.write_str("map"),
888            Type::MapIndef => f.write_str("indefinite map"),
889            Type::Tag => f.write_str("tag"),
890            Type::Break => f.write_str("break"),
891            Type::Unknown => f.write_fmt(format_args!("<unknown>"))write!(f, "<unknown>"),
892        }
893    }
894}
895
896/// Representation of possible CBOR tokens.
897#[derive(#[automatically_derived]
impl<'b> ::core::fmt::Debug for Token<'b> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Token::Bool(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Bool",
                    &__self_0),
            Token::Int(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Int",
                    &__self_0),
            Token::Float(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Float",
                    &__self_0),
            Token::Bytes(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Bytes",
                    &__self_0),
            Token::String(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "String",
                    &__self_0),
            Token::Array(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Array",
                    &__self_0),
            Token::Map(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Map",
                    &__self_0),
            Token::Tag(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Tag",
                    &__self_0),
            Token::Simple(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Simple",
                    &__self_0),
            Token::Break => ::core::fmt::Formatter::write_str(f, "Break"),
            Token::Null => ::core::fmt::Formatter::write_str(f, "Null"),
            Token::Undefined =>
                ::core::fmt::Formatter::write_str(f, "Undefined"),
            Token::BeginBytes =>
                ::core::fmt::Formatter::write_str(f, "BeginBytes"),
            Token::BeginString =>
                ::core::fmt::Formatter::write_str(f, "BeginString"),
            Token::BeginArray =>
                ::core::fmt::Formatter::write_str(f, "BeginArray"),
            Token::BeginMap =>
                ::core::fmt::Formatter::write_str(f, "BeginMap"),
        }
    }
}Debug, #[automatically_derived]
impl<'b> ::core::clone::Clone for Token<'b> {
    #[inline]
    fn clone(&self) -> Token<'b> {
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<num::Int>;
        let _: ::core::clone::AssertParamIsClone<f64>;
        let _: ::core::clone::AssertParamIsClone<&'b [u8]>;
        let _: ::core::clone::AssertParamIsClone<&'b str>;
        let _: ::core::clone::AssertParamIsClone<usize>;
        let _: ::core::clone::AssertParamIsClone<u64>;
        let _: ::core::clone::AssertParamIsClone<primitive::Simple>;
        *self
    }
}Clone, #[automatically_derived]
impl<'b> ::core::marker::Copy for Token<'b> { }Copy, #[automatically_derived]
impl<'b> ::core::cmp::PartialEq for Token<'b> {
    #[inline]
    fn eq(&self, other: &Token<'b>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Token::Bool(__self_0), Token::Bool(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Token::Int(__self_0), Token::Int(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Token::Float(__self_0), Token::Float(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Token::Bytes(__self_0), Token::Bytes(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Token::String(__self_0), Token::String(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Token::Array(__self_0), Token::Array(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Token::Map(__self_0), Token::Map(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Token::Tag(__self_0), Token::Tag(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Token::Simple(__self_0), Token::Simple(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
898pub enum Token<'b> {
899    Bool(bool),
900    Int(num::Int),
901    Float(f64),
902    Bytes(&'b [u8]),
903    String(&'b str),
904    Array(usize),
905    Map(usize),
906    Tag(u64),
907    Simple(primitive::Simple),
908    Break,
909    Null,
910    Undefined,
911    /// Start of indefinite byte string.
912    BeginBytes,
913    /// Start of indefinite text string.
914    BeginString,
915    /// Start of indefinite array.
916    BeginArray,
917    /// Start of indefinite map.
918    BeginMap,
919}
920
921/// Pretty print a token.
922///
923/// Since we only show a single token we can not use diagnostic notation
924/// as in the `Display` impl of [`Decoder`]. Instead, the following
925/// syntax is used:
926///
927/// - Numeric values and booleans are displayed as in Rust. Floats are always
928///   shown in scientific notation.
929/// - Text strings are displayed in double quotes.
930/// - Byte strings are displayed in single quotes prefixed with `h` and
931///   hex-encoded, e.g. `h'01 02 ef'`.
932/// - An array is displayed as `A[n]` where `n` denotes the number of elements.
933///   The following `n` tokens are elements of this array.
934/// - A map is displayed as `M[n]` where `n` denotes the number of pairs.
935///   The following `n` tokens are entries of this map.
936/// - Tags are displayed with `T(t)` where `t` is the tag number.
937/// - Simple values are displayed as `simple(n)` where `n` denotes the numeric
938///   value.
939/// - Indefinite items start with:
940///
941///     * `?B[` for byte strings,
942///     * `?S[` for text strings,
943///     * `?A[` for arrays,
944///     * `?M[` for maps,
945///
946///   and end with `]` when a `Token::Break` is encountered. All tokens
947///   in between belong to the indefinite container.
948/// - `Token::Null` is displayed as `null` and `Token::Undefined` as `undefined`.
949impl core::fmt::Display for Token<'_> {
950    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
951        match self {
952            Token::Bool(b) => f.write_fmt(format_args!("{0}", b))write!(f, "{b}"),
953            Token::Int(n) => f.write_fmt(format_args!("{0}", n))write!(f, "{n}"),
954            Token::Float(n) => f.write_fmt(format_args!("{0:e}", n))write!(f, "{n:e}"),
955            Token::String(n) => f.write_fmt(format_args!("\"{0}\"", n))write!(f, "\"{n}\""),
956            Token::Array(n) => f.write_fmt(format_args!("A[{0}]", n))write!(f, "A[{n}]"),
957            Token::Map(n) => f.write_fmt(format_args!("M[{0}]", n))write!(f, "M[{n}]"),
958            Token::Tag(t) => f.write_fmt(format_args!("T({0})", t))write!(f, "T({})", t),
959            Token::Simple(n) => f.write_fmt(format_args!("{0}", n))write!(f, "{n}"),
960            Token::Break => f.write_str("]"),
961            Token::Null => f.write_str("null"),
962            Token::Undefined => f.write_str("undefined"),
963            Token::BeginBytes => f.write_str("?B["),
964            Token::BeginString => f.write_str("?S["),
965            Token::BeginArray => f.write_str("?A["),
966            Token::BeginMap => f.write_str("?M["),
967            Token::Bytes(b) => {
968                f.write_str("h'")?;
969                let mut i = b.len();
970                for x in *b {
971                    if i > 1 {
972                        f.write_fmt(format_args!("{0:02x} ", x))write!(f, "{x:02x} ")?
973                    } else {
974                        f.write_fmt(format_args!("{0:02x}", x))write!(f, "{x:02x}")?
975                    }
976                    i -= 1;
977                }
978                f.write_str("'")
979            }
980        }
981    }
982}
983
984impl<'b> Decode<'b> for Token<'b> {
985    type Error = string::Error;
986
987    fn decode(d: &mut crate::Decoder<'b>) -> Result<Self, Self::Error> {
988        Ok(match d.datatype().map_err(primitive::Error::EndOfInput)? {
989            Type::Bool => Token::Bool(bool::decode(d)?),
990            Type::Int => Token::Int(num::Int::decode(d)?),
991            Type::Float => Token::Float(f64::decode(d)?),
992            Type::Bytes => Token::Bytes(<&'b [u8]>::decode(d)?),
993            Type::String => Token::String(<&'b str>::decode(d)?),
994            Type::Tag => Token::Tag(d.unsigned()?),
995            Type::Simple => Token::Simple(primitive::Simple::decode(d)?),
996            Type::Array => Token::Array(d.array_visitor()?.remaining().expect("known length")),
997            Type::Map => Token::Map(d.map_visitor()?.remaining().expect("known length")),
998            Type::BytesIndef => {
999                d.read().expect("byte was peeked in datatype");
1000                Token::BeginBytes
1001            }
1002            Type::StringIndef => {
1003                d.read().expect("byte was peeked in datatype");
1004                Token::BeginString
1005            }
1006            Type::ArrayIndef => {
1007                d.read().expect("byte was peeked in datatype");
1008                Token::BeginArray
1009            }
1010            Type::MapIndef => {
1011                d.read().expect("byte was peeked in datatype");
1012                Token::BeginMap
1013            }
1014            Type::Null => {
1015                d.read().expect("byte was peeked in datatype");
1016                Token::Null
1017            }
1018            Type::Undefined => {
1019                d.read().expect("byte was peeked in datatype");
1020                Token::Undefined
1021            }
1022            Type::Break => {
1023                d.read().expect("byte was peeked in datatype");
1024                Token::Break
1025            }
1026            Type::Unknown => {
1027                return Err(string::Error::Malformed(primitive::Error::InvalidHeader(
1028                    InvalidHeader,
1029                )));
1030            }
1031        })
1032    }
1033}
1034
1035/// Encodes as a tagged byte string, where the content is the CBOR encoding of `T`.
1036///
1037/// Uses [`IanaTag::Cbor`][tag::IanaTag::Cbor] as the tag.
1038#[derive(#[automatically_derived]
impl<T: ::core::fmt::Debug + ?Sized> ::core::fmt::Debug for Encoded<T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Encoded",
            &&self.0)
    }
}Debug, #[automatically_derived]
impl<T: ::core::clone::Clone + ?Sized> ::core::clone::Clone for Encoded<T> {
    #[inline]
    fn clone(&self) -> Encoded<T> {
        Encoded(::core::clone::Clone::clone(&self.0))
    }
}Clone, #[automatically_derived]
impl<T: ::core::marker::Copy + ?Sized> ::core::marker::Copy for Encoded<T> { }Copy, #[automatically_derived]
impl<T: ::core::default::Default + ?Sized> ::core::default::Default for
    Encoded<T> {
    #[inline]
    fn default() -> Encoded<T> {
        Encoded(::core::default::Default::default())
    }
}Default, #[automatically_derived]
impl<T: ::core::cmp::PartialEq + ?Sized> ::core::cmp::PartialEq for Encoded<T>
    {
    #[inline]
    fn eq(&self, other: &Encoded<T>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<T: ::core::cmp::Eq + ?Sized> ::core::cmp::Eq for Encoded<T> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<T>;
    }
}Eq, #[automatically_derived]
impl<T: ::core::cmp::PartialOrd + ?Sized> ::core::cmp::PartialOrd for
    Encoded<T> {
    #[inline]
    fn partial_cmp(&self, other: &Encoded<T>)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::cmp::PartialOrd::partial_cmp(&self.0, &other.0)
    }
}PartialOrd, #[automatically_derived]
impl<T: ::core::cmp::Ord + ?Sized> ::core::cmp::Ord for Encoded<T> {
    #[inline]
    fn cmp(&self, other: &Encoded<T>) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.0, &other.0)
    }
}Ord, #[automatically_derived]
impl<T: ::core::hash::Hash + ?Sized> ::core::hash::Hash for Encoded<T> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
1039#[repr(transparent)]
1040pub struct Encoded<T: ?Sized>(pub T);
1041
1042impl<T> Encoded<T> {
1043    /// Unwrap the inner value.
1044    pub fn into(self) -> T {
1045        self.0
1046    }
1047}
1048
1049impl<T> From<T> for Encoded<T> {
1050    fn from(value: T) -> Self {
1051        Encoded(value)
1052    }
1053}
1054
1055impl<T: ?Sized> From<&T> for &Encoded<T> {
1056    fn from(value: &T) -> Self {
1057        // Safety: `Encoded<T>` is `repr(transparent)` over `T`.
1058        unsafe { &*(value as *const T as *const Encoded<T>) }
1059    }
1060}
1061
1062impl<T: ?Sized> AsRef<T> for Encoded<T> {
1063    fn as_ref(&self) -> &T {
1064        &self.0
1065    }
1066}
1067
1068impl<T: ?Sized> AsMut<T> for Encoded<T> {
1069    fn as_mut(&mut self) -> &mut T {
1070        &mut self.0
1071    }
1072}
1073
1074impl<T: ?Sized> core::ops::Deref for Encoded<T> {
1075    type Target = T;
1076
1077    fn deref(&self) -> &Self::Target {
1078        &self.0
1079    }
1080}
1081
1082impl<T: ?Sized> core::ops::DerefMut for Encoded<T> {
1083    fn deref_mut(&mut self) -> &mut Self::Target {
1084        &mut self.0
1085    }
1086}
1087
1088impl<T: ?Sized + CborLen> CborLen for Encoded<T> {
1089    fn cbor_len(&self) -> usize {
1090        let len = self.0.cbor_len();
1091        (tag::IanaTag::Cbor as u64).cbor_len() + len.cbor_len() + len
1092    }
1093}
1094
1095impl<T: ?Sized + Encode + CborLen> Encode for Encoded<T> {
1096    fn encode<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), W::Error> {
1097        e.type_len(TAGGED, tag::IanaTag::Cbor as u64)?;
1098        e.type_len(BYTES, self.0.cbor_len() as u64)?;
1099        self.0.encode(e)
1100    }
1101}
1102
1103impl<'b, T: Decode<'b>> Decode<'b> for Encoded<T> {
1104    type Error = tag::Error<collections::Error<T::Error>>;
1105
1106    fn decode(d: &mut Decoder<'b>) -> Result<Self, Self::Error> {
1107        let tag::Tagged(bytes) = tag::Tagged::<&'b [u8], { tag::IanaTag::Cbor as u64 }>::decode(d)
1108            .map_err(|e| match e {
1109                tag::Error::InvalidTag => tag::Error::InvalidTag,
1110                tag::Error::Inner(e) => tag::Error::Inner(collections::Error::Malformed(e)),
1111                tag::Error::Malformed(e) => tag::Error::Malformed(e),
1112            })?;
1113
1114        let mut inner_decoder = Decoder(bytes);
1115        T::decode(&mut inner_decoder)
1116            .map(Encoded)
1117            .map_err(|e| tag::Error::Inner(collections::Error::Element(e)))
1118    }
1119}
1120
1121/// Decodes any CBOR data item, keeping its original encoding.
1122///
1123/// This can be useful to skip over unknown data items while preserving their exact encoding.
1124#[cfg(feature = "alloc")]
1125#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for Any<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Any", &&self.0)
    }
}Debug, #[automatically_derived]
impl<'a> ::core::clone::Clone for Any<'a> {
    #[inline]
    fn clone(&self) -> Any<'a> {
        let _: ::core::clone::AssertParamIsClone<&'a [u8]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for Any<'a> { }Copy, #[automatically_derived]
impl<'a> ::core::cmp::PartialEq for Any<'a> {
    #[inline]
    fn eq(&self, other: &Any<'a>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'a> ::core::cmp::Eq for Any<'a> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<&'a [u8]>;
    }
}Eq, #[automatically_derived]
impl<'a> ::core::cmp::PartialOrd for Any<'a> {
    #[inline]
    fn partial_cmp(&self, other: &Any<'a>)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::cmp::PartialOrd::partial_cmp(&self.0, &other.0)
    }
}PartialOrd, #[automatically_derived]
impl<'a> ::core::cmp::Ord for Any<'a> {
    #[inline]
    fn cmp(&self, other: &Any<'a>) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.0, &other.0)
    }
}Ord, #[automatically_derived]
impl<'a> ::core::hash::Hash for Any<'a> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
1126pub struct Any<'a>(&'a [u8]);
1127
1128#[cfg(feature = "alloc")]
1129impl<'a> core::ops::Deref for Any<'a> {
1130    type Target = &'a [u8];
1131
1132    fn deref(&self) -> &Self::Target {
1133        &self.0
1134    }
1135}
1136
1137#[cfg(feature = "alloc")]
1138impl<'a> core::convert::AsRef<[u8]> for Any<'a> {
1139    fn as_ref(&self) -> &[u8] {
1140        self.0
1141    }
1142}
1143
1144#[cfg(feature = "alloc")]
1145impl<'a> Decode<'a> for Any<'a> {
1146    type Error = string::Error;
1147
1148    fn decode(d: &mut Decoder<'a>) -> Result<Self, Self::Error> {
1149        use alloc::{vec, vec::Vec};
1150
1151        enum Frame {
1152            Count(usize),
1153            IndefArray,
1154            IndefMap,
1155            IndefBytes,
1156            IndefString,
1157        }
1158        fn top(stack: &[Frame]) -> &Frame {
1159            stack.last().expect("stack is non-empty")
1160        }
1161        fn invalid_header() -> string::Error {
1162            string::Error::Malformed(primitive::Error::InvalidHeader(InvalidHeader))
1163        }
1164
1165        let mut stack: Vec<Frame> = <[_]>::into_vec(::alloc::boxed::box_new([Frame::Count(0)]))vec![Frame::Count(0)];
1166        let start = d.0;
1167
1168        'outer: loop {
1169            let token = Token::decode(d)?;
1170            if (#[allow(non_exhaustive_omitted_patterns)] match top(&stack) {
    Frame::IndefBytes => true,
    _ => false,
}matches!(top(&stack), Frame::IndefBytes)
1171                && !#[allow(non_exhaustive_omitted_patterns)] match token {
    Token::Bytes(_) | Token::Break => true,
    _ => false,
}matches!(token, Token::Bytes(_) | Token::Break))
1172                || (#[allow(non_exhaustive_omitted_patterns)] match top(&stack) {
    Frame::IndefString => true,
    _ => false,
}matches!(top(&stack), Frame::IndefString)
1173                    && !#[allow(non_exhaustive_omitted_patterns)] match token {
    Token::String(_) | Token::Break => true,
    _ => false,
}matches!(token, Token::String(_) | Token::Break))
1174            {
1175                return Err(invalid_header());
1176            }
1177
1178            match token {
1179                Token::Array(count) => stack.push(Frame::Count(count)),
1180                Token::Map(count) => stack.push(Frame::Count(count * 2)),
1181
1182                Token::BeginBytes => stack.push(Frame::IndefBytes),
1183                Token::BeginString => stack.push(Frame::IndefString),
1184                Token::BeginArray => stack.push(Frame::IndefArray),
1185                Token::BeginMap => stack.push(Frame::IndefMap),
1186                Token::Break if !#[allow(non_exhaustive_omitted_patterns)] match top(&stack) {
    Frame::Count(_) => true,
    _ => false,
}matches!(top(&stack), Frame::Count(_)) => {
1187                    stack.pop();
1188                }
1189                Token::Break => return Err(invalid_header()),
1190
1191                _ => {}
1192            }
1193
1194            loop {
1195                match stack.last() {
1196                    Some(Frame::Count(0)) => {
1197                        stack.pop();
1198                    }
1199                    Some(Frame::Count(n)) => {
1200                        let n = *n - 1;
1201                        *stack.last_mut().expect("stack is non-empty") = Frame::Count(n);
1202                        break;
1203                    }
1204                    None => break 'outer,
1205                    _ => break,
1206                }
1207            }
1208        }
1209
1210        let end = d.0;
1211        let len = start.len() - end.len();
1212        Ok(Any(&start[..len]))
1213    }
1214}
1215
1216#[cfg(feature = "alloc")]
1217impl Encode for Any<'_> {
1218    fn encode<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), W::Error> {
1219        e.0.write_all(self.0)
1220    }
1221}
1222
1223#[cfg(feature = "alloc")]
1224impl CborLen for Any<'_> {
1225    fn cbor_len(&self) -> usize {
1226        self.0.len()
1227    }
1228}
1229
1230/// Returns `true` if `value.encode() == bytes`, false otherwise.
1231///
1232/// Panics when:
1233/// - The encoded size is greater than `16KB.
1234/// - The value decoded from `bytes` is not equal to `value`.
1235/// - `value.cbor_len() != <encoded-len>`.
1236#[cfg(test)]
1237fn test<'a, T>(value: T, bytes: &'a [u8]) -> Result<bool, T::Error>
1238where
1239    T: Decode<'a> + Encode + CborLen + core::cmp::PartialEq + core::fmt::Debug,
1240{
1241    let mut buffer = Vec::new();
1242    value.encode(&mut Encoder(&mut buffer));
1243    assert_eq!(
1244        value.cbor_len(),
1245        buffer.len(),
1246        "cbor_len does not match actual length"
1247    );
1248    let decoded = T::decode(&mut Decoder(bytes))?;
1249    assert_eq!(value, decoded, "decoded value does not match original");
1250    Ok(buffer.as_slice() == bytes)
1251}
1252
1253#[cfg(test)]
1254mod tests {
1255    use core::num::NonZeroU8;
1256
1257    use crate::{Any, Decode, Decoder, Encode, Encoder, primitive::Undefined};
1258
1259    #[test]
1260    fn any() {
1261        let mut encoder = Encoder(Vec::new());
1262
1263        encoder.map(3);
1264        u32::MAX.encode(&mut encoder);
1265        "hello world".encode(&mut encoder);
1266        encoder.array(2);
1267        true.encode(&mut encoder);
1268        core::f64::consts::PI.encode(&mut encoder);
1269        Undefined.encode(&mut encoder);
1270        encoder.begin_map();
1271        encoder.begin_str();
1272        "key".encode(&mut encoder);
1273        encoder.end();
1274        encoder.begin_array();
1275        [3, 1, 4, 1, 5].encode(&mut encoder);
1276        [3u8, 1, 4, 1, 5].encode(&mut encoder);
1277        encoder.end();
1278        encoder.end();
1279        encoder.begin_bytes();
1280        encoder.end();
1281
1282        Any::decode(&mut Decoder(&encoder.0)).unwrap();
1283    }
1284}