Skip to main content

deser_cbor/
raw.rs

1//! Raw values of CBOR.
2use alloc::vec::Vec;
3
4use deser_core::de::{self, DeserializeDriver};
5use deser_core::ext::{Raw, RawFormat, RawFormatId, RawFormatInfo};
6use deser_core::ser::SerializeRef;
7use deser_core::{Atom, Bytes, Error};
8
9use crate::de::Deserializer;
10use crate::parser::Cursor;
11
12/// The CBOR format of [`RawCbor`] values.
13pub struct Cbor;
14
15/// The CBOR encoding of a value.
16///
17/// Values deserialized from CBOR keep their encoding as it is (including
18/// their tags), other values are encoded as CBOR.  When serialized with
19/// CBOR (unless canonical output is requested), the encoding is written as
20/// it is.  See [raw values](crate#raw-values) and [`Raw`] for more
21/// information.
22pub type RawCbor<'a> = Raw<'a, Cbor>;
23
24/// The identity of the format of raw CBOR values.
25///
26/// The parser and the serializer declare the raw values they pass on with
27/// it, the description (with the functions) is only referred to by the raw
28/// values.
29pub(crate) static ID: RawFormatId = RawFormatId::new("cbor", false);
30
31/// The description of the format of raw CBOR values.
32static FORMAT: RawFormatInfo = {
33    let mut info = RawFormatInfo::new(&ID, replay, encode, fallback);
34    info.set_data(&SCANNER);
35    info
36};
37
38/// Skips an item while validating it (see `Parser::raw_values`).
39///
40/// The parser gets it from the description of the format, so that only
41/// programs with raw values of the format contain it.
42pub(crate) struct Scanner(pub(crate) ScanFn);
43
44/// Skips the item at the cursor (see `parser::skip_raw`).
45type ScanFn = for<'i> fn(&mut Cursor<'i>, &mut Vec<u8>) -> Result<(), Error>;
46
47/// The scanner of raw values.
48static SCANNER: Scanner = Scanner(crate::parser::skip_raw);
49
50impl RawFormat for Cbor {
51    #[inline(always)]
52    fn info() -> &'static RawFormatInfo {
53        &FORMAT
54    }
55}
56
57/// Parses a raw value.
58fn replay<'de>(input: &'de [u8], driver: &mut DeserializeDriver<'_, 'de>) -> Result<(), Error> {
59    de::Deserializer::drive(&mut Deserializer::from_slice(input), driver)
60}
61
62/// Encodes a value.
63fn encode(value: SerializeRef<'_>) -> Result<Vec<u8>, Error> {
64    crate::to_vec(&value)
65}
66
67/// Returns the fallback atom of a raw value.
68///
69/// Null (and undefined) and booleans are their value, everything else is
70/// its encoding as bytes.
71fn fallback(input: &[u8]) -> Atom<'_> {
72    match input {
73        [0xf6 | 0xf7] => Atom::Null,
74        [0xf4] => Atom::Bool(false),
75        [0xf5] => Atom::Bool(true),
76        _ => Atom::Bytes(Bytes::borrowed(input)),
77    }
78}