Skip to main content

deser_msgpack/
raw.rs

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