musli_core/de/
decode_packed.rs

1use super::Decoder;
2
3/// Trait governing how a type is decoded as a packed value.
4///
5/// Packed encodings are ones where data follow one after another, with no
6/// "metadata" indicating when one value starts and another stops.
7///
8/// This is typically used automatically through the `#[musli(packed)]`
9/// attribute through the [`Decode` derive].
10///
11/// [`Decode` derive]: https://docs.rs/musli/latest/musli/help/derives/
12///
13/// # Examples
14///
15/// ```
16/// use musli::Decode;
17///
18/// #[derive(Decode)]
19/// struct Packed {
20///     #[musli(packed)]
21///     data: (u32, u32),
22/// }
23/// ```
24///
25/// Implementing manually:
26///
27/// ```
28/// use musli::{Decode, Decoder};
29/// use musli::de::SequenceDecoder;
30///
31/// struct Packed {
32///     data: (u32, u32),
33/// }
34///
35/// impl<'de, M> Decode<'de, M> for Packed {
36///     fn decode<D>(cx: &D::Cx, decoder: D) -> Result<Self, D::Error>
37///     where
38///         D: Decoder<'de>,
39///     {
40///         decoder.decode_pack(|pack| {
41///             Ok(Self {
42///                 data: (pack.next()?, pack.next()?),
43///             })
44///         })
45///     }
46/// }
47/// ```
48pub trait DecodePacked<'de, M>: Sized {
49    /// Decode the given input as bytes.
50    fn decode_packed<D>(cx: &D::Cx, decoder: D) -> Result<Self, D::Error>
51    where
52        D: Decoder<'de, Mode = M>;
53}