bincode_next/enc/mod.rs
1//! Encoder-based structs and traits.
2
3mod encoder;
4mod impl_tuples;
5mod impls;
6
7use self::write::Writer;
8use crate::{config::Config, error::EncodeError, utils::Sealed};
9
10pub mod write;
11
12pub use self::encoder::EncoderImpl;
13
14/// Any source that can be encoded. This trait should be implemented for all types that you want to be able to use with any of the `encode_with` methods.
15///
16/// This trait will be automatically implemented if you enable the `derive` feature and add `#[derive(bincode::Encode)]` to your trait.
17///
18/// # Implementing this trait manually
19///
20/// If you want to implement this trait for your type, the easiest way is to add a `#[derive(bincode::Encode)]`, build and check your `target/generated/bincode/` folder. This should generate a `<Struct name>_Encode.rs` file.
21///
22/// For this struct:
23///
24/// ```
25/// struct Entity {
26/// pub x: f32,
27/// pub y: f32,
28/// }
29/// ```
30/// It will look something like:
31///
32/// ```
33/// # struct Entity {
34/// # pub x: f32,
35/// # pub y: f32,
36/// # }
37/// impl bincode_next::Encode for Entity {
38/// fn encode<E: bincode_next::enc::Encoder>(
39/// &self,
40/// encoder: &mut E,
41/// ) -> core::result::Result<(), bincode_next::error::EncodeError> {
42/// bincode_next::Encode::encode(&self.x, encoder)?;
43/// bincode_next::Encode::encode(&self.y, encoder)?;
44/// Ok(())
45/// }
46/// }
47/// ```
48///
49/// From here you can add/remove fields, or add custom logic.
50pub trait Encode {
51 /// Encode a given type.
52 ///
53 /// # Errors
54 ///
55 /// Returns any error encountered during encoding.
56 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError>;
57}
58
59/// Helper trait to encode basic types into.
60pub trait Encoder: Sealed {
61 /// The concrete [Writer] type
62 type W: Writer;
63
64 /// The concrete [Config] type
65 type C: Config;
66
67 /// Returns a mutable reference to the writer
68 fn writer(&mut self) -> &mut Self::W;
69
70 /// Returns a reference to the config
71 fn config(&self) -> &Self::C;
72}
73
74impl<T> Encoder for &mut T
75where
76 T: Encoder,
77{
78 type W = T::W;
79
80 type C = T::C;
81
82 fn writer(&mut self) -> &mut Self::W {
83 T::writer(self)
84 }
85
86 fn config(&self) -> &Self::C {
87 T::config(self)
88 }
89}
90
91/// Encode the variant of the given option. Will not encode the option itself.
92#[inline]
93pub(crate) fn encode_option_variant<E: Encoder, T>(
94 encoder: &mut E,
95 value: Option<&T>,
96) -> Result<(), EncodeError> {
97 match value {
98 None => 0u8.encode(encoder),
99 Some(_) => 1u8.encode(encoder),
100 }
101}
102
103/// Encodes the length of any slice, container, etc into the given encoder
104#[inline]
105pub(crate) fn encode_slice_len<E: Encoder>(encoder: &mut E, len: usize) -> Result<(), EncodeError> {
106 (len as u64).encode(encoder)
107}