musli_core/de/
decode.rs

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