musli_core/en/encode.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
use crate::en::Encoder;
/// Trait governing how types are encoded.
///
/// This is typically implemented automatically using the [`Encode` derive].
///
/// [`Encode` derive]: https://docs.rs/musli/latest/musli/help/derives/
///
/// # Examples
///
/// ```
/// use musli::Encode;
///
/// #[derive(Encode)]
/// struct MyType {
/// data: [u8; 128],
/// }
/// ```
///
/// Implementing manually:
///
/// ```
/// use musli::{Encode, Encoder};
///
/// struct MyType {
/// data: [u8; 128],
/// }
///
/// impl<M> Encode<M> for MyType {
/// fn encode<E>(&self, cx: &E::Cx, encoder: E) -> Result<E::Ok, E::Error>
/// where
/// E: Encoder<Mode = M>,
/// {
/// encoder.encode_array(&self.data)
/// }
/// }
/// ```
pub trait Encode<M> {
/// Encode the given output.
fn encode<E>(&self, cx: &E::Cx, encoder: E) -> Result<E::Ok, E::Error>
where
E: Encoder<Mode = M>;
}
impl<T, M> Encode<M> for &T
where
T: ?Sized + Encode<M>,
{
#[inline]
fn encode<E>(&self, cx: &E::Cx, encoder: E) -> Result<E::Ok, E::Error>
where
E: Encoder<Mode = M>,
{
(**self).encode(cx, encoder)
}
}
impl<T, M> Encode<M> for &mut T
where
T: ?Sized + Encode<M>,
{
#[inline]
fn encode<E>(&self, cx: &E::Cx, encoder: E) -> Result<E::Ok, E::Error>
where
E: Encoder<Mode = M>,
{
(**self).encode(cx, encoder)
}
}