Skip to main content

musli_core/de/
decode_owned.rs

1use crate::Allocator;
2#[cfg(feature = "alloc")]
3use crate::alloc::Global;
4
5use super::Decode;
6
7/// Decode to an owned value.
8///
9/// This is a simpler bound to use than `for<'de> Decode<'de, M, A>`, and is
10/// what you want when a function needs to decode a value which doesn't borrow
11/// from the input, such as when it is decoded from a temporary buffer.
12///
13/// With the `alloc` feature enabled the allocator defaults to [`Global`], so
14/// the bound can be written as just `DecodeOwned<Binary>`. Without it the
15/// allocator must be specified.
16///
17/// # Examples
18///
19/// ```
20/// use musli::DecodeOwned;
21/// use musli::mode::Binary;
22/// use musli::{Decode, Encode};
23///
24/// #[derive(Encode, Decode)]
25/// struct Data {
26///     value: u32,
27/// }
28///
29/// fn roundtrip<T>(value: &T) -> T
30/// where
31///     T: Encode<Binary> + DecodeOwned<Binary>,
32/// {
33///     let bytes = musli::storage::to_vec(value).unwrap();
34///     musli::storage::from_slice(&bytes[..]).unwrap()
35/// }
36///
37/// assert_eq!(roundtrip(&Data { value: 42 }).value, 42);
38/// ```
39#[cfg(feature = "alloc")]
40pub trait DecodeOwned<M, A = Global>: for<'de> Decode<'de, M, A>
41where
42    A: Allocator,
43{
44}
45
46/// Decode to an owned value.
47///
48/// This is a simpler bound to use than `for<'de> Decode<'de, M, A>`.
49///
50/// With the `alloc` feature enabled the allocator defaults to `Global`.
51#[cfg(not(feature = "alloc"))]
52pub trait DecodeOwned<M, A>: for<'de> Decode<'de, M, A>
53where
54    A: Allocator,
55{
56}
57
58impl<M, D, A> DecodeOwned<M, A> for D
59where
60    D: for<'de> Decode<'de, M, A>,
61    A: Allocator,
62{
63}