Debian Codegraph @

src/enc/mod.rs

raw
1 //! Encoder-based structs and traits.
2
3 mod encoder;
4 mod impl_tuples;
5 mod impls;
6
7 use self::write::Writer;
8 use crate::{config::Config, error::EncodeError, utils::Sealed};
9
10 pub mod write;
11
12 pub 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::Encode for Entity {
38 /// fn encode<E: bincode::enc::Encoder>(
39 /// &self,
40 /// encoder: &mut E,
41 /// ) -> core::result::Result<(), bincode::error::EncodeError> {
42 /// bincode::Encode::encode(&self.x, encoder)?;
43 /// bincode::Encode::encode(&self.y, encoder)?;
44 /// Ok(())
45 /// }
46 /// }
47 /// ```
48 ///
49 /// From here you can add/remove fields, or add custom logic.
50 pub trait Encode {
51 /// Encode a given type.
52 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError>;
53 }
54
55 /// Helper trait to encode basic types into.
56 pub trait Encoder: Sealed {
57 /// The concrete [Writer] type
58 type W: Writer;
59
60 /// The concrete [Config] type
61 type C: Config;
62
63 /// Returns a mutable reference to the writer
64 fn writer(&mut self) -> &mut Self::W;
65
66 /// Returns a reference to the config
67 fn config(&self) -> &Self::C;
68 }
69
70 impl<T> Encoder for &mut T
71 where
72 T: Encoder,
73 {
74 type W = T::W;
75
76 type C = T::C;
77
78 fn writer(&mut self) -> &mut Self::W {
79 T::writer(self)
80 }
81
82 fn config(&self) -> &Self::C {
83 T::config(self)
84 }
85 }
86
87 /// Encode the variant of the given option. Will not encode the option itself.
88 #[inline]
89 pub(crate) fn encode_option_variant<E: Encoder, T>(
90 encoder: &mut E,
91 value: &Option<T>,
92 ) -> Result<(), EncodeError> {
93 match value {
94 None => 0u8.encode(encoder),
95 Some(_) => 1u8.encode(encoder),
96 }
97 }
98
99 /// Encodes the length of any slice, container, etc into the given encoder
100 #[inline]
101 pub(crate) fn encode_slice_len<E: Encoder>(encoder: &mut E, len: usize) -> Result<(), EncodeError> {
102 (len as u64).encode(encoder)
103 }