musli_core/de/
decode_packed.rs

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