musli_core/de/decode_bytes.rs
1use crate::Allocator;
2
3use super::Decoder;
4
5/// Trait governing how types are decoded as bytes.
6///
7/// This is typically used automatically through the `#[musli(bytes)]` attribute
8/// through the [`Decode` derive].
9///
10/// [`Decode` derive]: https://docs.rs/musli/latest/musli/_help/derives/
11///
12/// # Examples
13///
14/// ```
15/// use musli::Decode;
16///
17/// #[derive(Decode)]
18/// struct MyType {
19/// #[musli(bytes)]
20/// data: [u8; 128],
21/// }
22/// ```
23///
24/// Implementing manually:
25///
26/// ```
27/// use musli::{Allocator, Decode, Decoder};
28/// use musli::de::DecodeBytes;
29///
30/// struct MyType {
31/// data: [u8; 128],
32/// }
33///
34/// impl<'de, M, A> Decode<'de, M, A> for MyType
35/// where
36/// A: Allocator,
37/// {
38/// #[inline]
39/// fn decode<D>(decoder: D) -> Result<Self, D::Error>
40/// where
41/// D: Decoder<'de>,
42/// {
43/// Ok(Self {
44/// data: DecodeBytes::decode_bytes(decoder)?,
45/// })
46/// }
47/// }
48/// ```
49pub trait DecodeBytes<'de, M, A>: Sized
50where
51 A: Allocator,
52{
53 /// Whether the type is packed. Packed types can be bitwise copied if the
54 /// representation of the serialization format is identical to the memory
55 /// layout of the type.
56 ///
57 /// Note that setting this to `true` has safety implications, since it
58 /// implies that assuming the type is correctly aligned it can be validly
59 /// bitwise copied when encoded. Setting it to `false` is always safe.
60 const DECODE_BYTES_PACKED: bool = false;
61
62 /// Decode the given input as bytes.
63 fn decode_bytes<D>(decoder: D) -> Result<Self, D::Error>
64 where
65 D: Decoder<'de, Mode = M, Allocator = A>;
66}