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/// fn encode<E>(&self, cx: &E::Cx, encoder: E) -> Result<E::Ok, E::Error>
37/// where
38/// E: Encoder,
39/// {
40/// let mut pack = encoder.encode_pack()?;
41/// pack.push(&self.data.0);
42/// pack.push(&self.data.1);
43/// pack.finish_sequence()
44/// }
45/// }
46/// ```
47pub trait EncodePacked<M> {
48 /// Encode the given output as bytes.
49 fn encode_packed<E>(&self, cx: &E::Cx, encoder: E) -> Result<E::Ok, E::Error>
50 where
51 E: Encoder<Mode = M>;
52}
53
54impl<T, M> EncodePacked<M> for &T
55where
56 T: ?Sized + EncodePacked<M>,
57{
58 #[inline]
59 fn encode_packed<E>(&self, cx: &E::Cx, encoder: E) -> Result<E::Ok, E::Error>
60 where
61 E: Encoder<Mode = M>,
62 {
63 (**self).encode_packed(cx, encoder)
64 }
65}
66
67impl<T, M> EncodePacked<M> for &mut T
68where
69 T: ?Sized + EncodePacked<M>,
70{
71 #[inline]
72 fn encode_packed<E>(&self, cx: &E::Cx, encoder: E) -> Result<E::Ok, E::Error>
73 where
74 E: Encoder<Mode = M>,
75 {
76 (**self).encode_packed(cx, encoder)
77 }
78}