musli_core/en/
encode_packed.rs

1use crate::en::Encoder;
2
3/// Trait governing how a type is encoded 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::Encode;
17///
18/// #[derive(Encode)]
19/// struct PackedType {
20///     #[musli(packed)]
21///     data: (u32, u32),
22/// }
23/// ```
24///
25/// Implementing manually:
26///
27/// ```
28/// use musli::{Encode, Encoder};
29/// use musli::en::SequenceEncoder;
30///
31/// struct PackedType {
32///     data: (u32, u32),
33/// }
34///
35/// impl<M> Encode<M> for PackedType {
36///     type Encode = Self;
37///
38///     #[inline]
39///     fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
40///     where
41///         E: Encoder,
42///     {
43///         let mut pack = encoder.encode_pack()?;
44///         pack.push(&self.data.0);
45///         pack.push(&self.data.1);
46///         pack.finish_sequence()
47///     }
48///
49///     #[inline]
50///     fn as_encode(&self) -> &Self::Encode {
51///         self
52///     }
53/// }
54/// ```
55pub trait EncodePacked<M> {
56    /// Encode the given output as bytes.
57    fn encode_packed<E>(&self, encoder: E) -> Result<(), E::Error>
58    where
59        E: Encoder<Mode = M>;
60
61    /// The number of fields in the type.
62    #[inline]
63    fn size_hint(&self) -> Option<usize> {
64        None
65    }
66}
67
68impl<T, M> EncodePacked<M> for &T
69where
70    T: ?Sized + EncodePacked<M>,
71{
72    #[inline]
73    fn encode_packed<E>(&self, encoder: E) -> Result<(), E::Error>
74    where
75        E: Encoder<Mode = M>,
76    {
77        (**self).encode_packed(encoder)
78    }
79}
80
81impl<T, M> EncodePacked<M> for &mut T
82where
83    T: ?Sized + EncodePacked<M>,
84{
85    #[inline]
86    fn encode_packed<E>(&self, encoder: E) -> Result<(), E::Error>
87    where
88        E: Encoder<Mode = M>,
89    {
90        (**self).encode_packed(encoder)
91    }
92}