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.set_check_limits(crate::parser::check_raw_limits);
37 info
38};
39
40/// Skips an item while validating it (see `Parser::raw_values`).
41///
42/// The parser gets it from the description of the format, so that only
43/// programs with raw values of the format contain it.
44pub(crate) struct Scanner(pub(crate) ScanFn);
45
46/// Skips the item at the cursor (see `parser::skip_raw`).
47type ScanFn = for<'i> fn(&mut Cursor<'i>) -> Result<(), Error>;
48
49/// The scanner of raw values.
50static SCANNER: Scanner = Scanner(crate::parser::skip_raw);
51
52impl RawFormat for Msgpack {
53 #[inline(always)]
54 fn info() -> &'static RawFormatInfo {
55 &FORMAT
56 }
57}
58
59/// Parses a raw value.
60fn replay<'de>(input: &'de [u8], driver: &mut DeserializeDriver<'_, 'de>) -> Result<(), Error> {
61 de::Deserializer::drive(&mut Deserializer::from_slice(input), driver)
62}
63
64/// Encodes a value.
65fn encode(value: SerializeRef<'_>) -> Result<Vec<u8>, Error> {
66 crate::to_vec(&value)
67}
68
69/// Returns the fallback atom of a raw value.
70///
71/// Nil and booleans are their value, everything else is its encoding as
72/// bytes.
73fn fallback(input: &[u8]) -> Atom<'_> {
74 match input {
75 [0xc0] => Atom::Null,
76 [0xc2] => Atom::Bool(false),
77 [0xc3] => Atom::Bool(true),
78 _ => Atom::Bytes(Bytes::borrowed(input)),
79 }
80}