bincode_next/
config.rs

1//! The config module is used to change the behavior of bincode's encoding and decoding logic.
2//!
3//! *Important* make sure you use the same config for encoding and decoding, or else bincode will not work properly.
4//!
5//! To use a config, first create a type of [Configuration]. This type will implement trait [Config] for use with bincode.
6//!
7//! ```
8//! let config = bincode_next::config::standard()
9//!     // pick one of:
10//!     .with_big_endian()
11//!     .with_little_endian()
12//!     // pick one of:
13//!     .with_variable_int_encoding()
14//!     .with_fixed_int_encoding();
15//! ```
16//!
17//! See [Configuration] for more information on the configuration options.
18
19pub(crate) use self::internal::*;
20use core::marker::PhantomData;
21
22/// The Configuration struct is used to build bincode configurations. The [Config] trait is implemented
23/// by this struct when a valid configuration has been constructed.
24///
25/// The following methods are mutually exclusive and will overwrite each other. The last call to one of these methods determines the behavior of the configuration:
26///
27/// - [`with_little_endian`\] and [`with_big_endian`\]
28/// - [`with_fixed_int_encoding`\] and [`with_variable_int_encoding`\]
29///
30///
31/// [with_little_endian]: #method.with_little_endian
32/// [with_big_endian]: #method.with_big_endian
33/// [with_fixed_int_encoding]: #method.with_fixed_int_encoding
34/// [with_variable_int_encoding]: #method.with_variable_int_encoding
35#[derive(Copy, Clone, Debug)]
36pub struct Configuration<E = LittleEndian, I = Varint, L = NoLimit> {
37    _e: PhantomData<E>,
38    _i: PhantomData<I>,
39    _l: PhantomData<L>,
40}
41
42// When adding more features to configuration, follow these steps:
43// - Create 2 or more structs that can be used as a type (e.g. Limit and NoLimit)
44// - Add an `Internal...Config` to the `internal` module
45// - Make sure `Config` and `impl<T> Config for T` extend from this new trait
46// - Add a generic to `Configuration`
47// - Add this generic to `impl<...> Default for Configuration<...>`
48// - Add this generic to `const fn generate<...>()`
49// - Add this generic to _every_ function in `Configuration`
50// - Add your new methods
51
52/// The default config for bincode 2.0. By default this will be:
53/// - Little endian
54/// - Variable int encoding
55#[must_use]
56pub const fn standard() -> Configuration {
57    generate()
58}
59
60/// Creates the "legacy" default config. This is the default config that was present in bincode 1.0
61/// - Little endian
62/// - Fixed int length encoding
63#[must_use]
64pub const fn legacy() -> Configuration<LittleEndian, Fixint, NoLimit> {
65    generate()
66}
67
68impl<E, I, L> Default for Configuration<E, I, L> {
69    fn default() -> Self {
70        generate()
71    }
72}
73
74const fn generate<E, I, L>() -> Configuration<E, I, L> {
75    Configuration {
76        _e: PhantomData,
77        _i: PhantomData,
78        _l: PhantomData,
79    }
80}
81
82impl<E, I, L> Configuration<E, I, L> {
83    /// Makes bincode encode all integer types in big endian.
84    #[must_use]
85    pub const fn with_big_endian(self) -> Configuration<BigEndian, I, L> {
86        generate()
87    }
88
89    /// Makes bincode encode all integer types in little endian.
90    #[must_use]
91    pub const fn with_little_endian(self) -> Configuration<LittleEndian, I, L> {
92        generate()
93    }
94
95    /// Makes bincode encode all integer types with a variable integer encoding.
96    ///
97    /// Encoding an unsigned integer `v` (of any type excepting `u8`) works as follows:
98    ///
99    /// 1. If `u < 251`, encode it as a single byte with that value.
100    /// 2. If `251 <= u < 2**16`, encode it as a literal byte `251`, followed by a `u16` with value `u`.
101    /// 3. If `2**16 <= u < 2**32`, encode it as a literal byte `252`, followed by a `u32` with value `u`.
102    /// 4. If `2**32 <= u < 2**64`, encode it as a literal byte `253`, followed by a `u64` with value `u`.
103    /// 5. If `2**64 <= u < 2**128`, encode it as a literal byte `254`, followed by a `u128` with value `u`.
104    ///
105    /// Then, for signed integers, we first convert to unsigned using the zigzag algorithm,
106    /// and then encode them as we do for unsigned integers generally. The reason we use this
107    /// algorithm is that it encodes those values which are close to zero in less bytes; the
108    /// obvious algorithm, where we encode the cast values, gives a very large encoding for all
109    /// negative values.
110    ///
111    /// The zigzag algorithm is defined as follows:
112    ///
113    /// ```rust
114    /// # type Signed = i32;
115    /// # type Unsigned = u32;
116    /// fn zigzag(v: Signed) -> Unsigned {
117    ///     match v {
118    ///         0 => 0,
119    ///         // To avoid the edge case of Signed::min_value()
120    ///         // !n is equal to `-n - 1`, so this is:
121    ///         // !n * 2 + 1 = 2(-n - 1) + 1 = -2n - 2 + 1 = -2n - 1
122    ///         v if v < 0 => !(v as Unsigned) * 2 - 1,
123    ///         v if v > 0 => (v as Unsigned) * 2,
124    /// #       _ => unreachable!()
125    ///     }
126    /// }
127    /// ```
128    ///
129    /// And works such that:
130    ///
131    /// ```rust
132    /// # let zigzag = |n: i64| -> u64 {
133    /// #     match n {
134    /// #         0 => 0,
135    /// #         v if v < 0 => !(v as u64) * 2 + 1,
136    /// #         v if v > 0 => (v as u64) * 2,
137    /// #         _ => unreachable!(),
138    /// #     }
139    /// # };
140    /// assert_eq!(zigzag(0), 0);
141    /// assert_eq!(zigzag(-1), 1);
142    /// assert_eq!(zigzag(1), 2);
143    /// assert_eq!(zigzag(-2), 3);
144    /// assert_eq!(zigzag(2), 4);
145    /// // etc
146    /// assert_eq!(zigzag(i64::min_value()), u64::max_value());
147    /// ```
148    ///
149    /// Note that u256 and the like are unsupported by this format; if and when they are added to the
150    /// language, they may be supported via the extension point given by the 255 byte.
151    #[must_use]
152    pub const fn with_variable_int_encoding(self) -> Configuration<E, Varint, L> {
153        generate()
154    }
155
156    /// Fixed-size integer encoding.
157    ///
158    /// * Fixed size integers are encoded directly
159    /// * Enum discriminants are encoded as u32
160    /// * Lengths and usize are encoded as u64
161    #[must_use]
162    pub const fn with_fixed_int_encoding(self) -> Configuration<E, Fixint, L> {
163        generate()
164    }
165
166    /// Sets the byte limit to `limit`.
167    #[must_use]
168    pub const fn with_limit<const N: usize>(self) -> Configuration<E, I, Limit<N>> {
169        generate()
170    }
171
172    /// Clear the byte limit.
173    #[must_use]
174    pub const fn with_no_limit(self) -> Configuration<E, I, NoLimit> {
175        generate()
176    }
177}
178
179/// Indicates a type is valid for controlling the bincode configuration
180pub trait Config:
181    InternalEndianConfig + InternalIntEncodingConfig + InternalLimitConfig + Copy + Clone
182{
183    /// This configuration's Endianness
184    fn endianness(&self) -> Endianness;
185
186    /// This configuration's Integer Encoding
187    fn int_encoding(&self) -> IntEncoding;
188
189    /// This configuration's byte limit, or `None` if no limit is configured
190    fn limit(&self) -> Option<usize>;
191}
192
193impl<T> Config for T
194where
195    T: InternalEndianConfig + InternalIntEncodingConfig + InternalLimitConfig + Copy + Clone,
196{
197    fn endianness(&self) -> Endianness {
198        <T as InternalEndianConfig>::ENDIAN
199    }
200
201    fn int_encoding(&self) -> IntEncoding {
202        <T as InternalIntEncodingConfig>::INT_ENCODING
203    }
204
205    fn limit(&self) -> Option<usize> {
206        <T as InternalLimitConfig>::LIMIT
207    }
208}
209
210/// Encodes all integer types in big endian.
211#[derive(Copy, Clone, Debug)]
212pub struct BigEndian;
213
214impl InternalEndianConfig for BigEndian {
215    const ENDIAN: Endianness = Endianness::Big;
216}
217
218/// Encodes all integer types in little endian.
219#[derive(Copy, Clone, Debug)]
220pub struct LittleEndian;
221
222impl InternalEndianConfig for LittleEndian {
223    const ENDIAN: Endianness = Endianness::Little;
224}
225
226/// Use fixed-size integer encoding.
227#[derive(Copy, Clone, Debug)]
228pub struct Fixint;
229
230impl InternalIntEncodingConfig for Fixint {
231    const INT_ENCODING: IntEncoding = IntEncoding::Fixed;
232}
233
234/// Use variable integer encoding.
235#[derive(Copy, Clone, Debug)]
236pub struct Varint;
237
238impl InternalIntEncodingConfig for Varint {
239    const INT_ENCODING: IntEncoding = IntEncoding::Variable;
240}
241
242/// Sets an unlimited byte limit.
243#[derive(Copy, Clone, Debug)]
244pub struct NoLimit;
245impl InternalLimitConfig for NoLimit {
246    const LIMIT: Option<usize> = None;
247}
248
249/// Sets the byte limit to N.
250#[derive(Copy, Clone, Debug)]
251pub struct Limit<const N: usize>;
252impl<const N: usize> InternalLimitConfig for Limit<N> {
253    const LIMIT: Option<usize> = Some(N);
254}
255
256/// Endianness of a `Configuration`.
257#[derive(Copy, Clone, Debug, PartialEq, Eq)]
258#[non_exhaustive]
259pub enum Endianness {
260    /// Little Endian encoding, see `LittleEndian`.
261    Little,
262    /// Big Endian encoding, see `BigEndian`.
263    Big,
264}
265
266/// Integer Encoding of a `Configuration`.
267#[derive(Copy, Clone, Debug, PartialEq, Eq)]
268#[non_exhaustive]
269pub enum IntEncoding {
270    /// Fixed Integer Encoding, see `Fixint`.
271    Fixed,
272    /// Variable Integer Encoding, see `Varint`.
273    Variable,
274}
275
276mod internal {
277    use super::{Configuration, Endianness, IntEncoding};
278
279    pub trait InternalEndianConfig {
280        const ENDIAN: Endianness;
281    }
282
283    impl<E: InternalEndianConfig, I, L> InternalEndianConfig for Configuration<E, I, L> {
284        const ENDIAN: Endianness = E::ENDIAN;
285    }
286
287    pub trait InternalIntEncodingConfig {
288        const INT_ENCODING: IntEncoding;
289    }
290
291    impl<E, I: InternalIntEncodingConfig, L> InternalIntEncodingConfig for Configuration<E, I, L> {
292        const INT_ENCODING: IntEncoding = I::INT_ENCODING;
293    }
294
295    pub trait InternalLimitConfig {
296        const LIMIT: Option<usize>;
297    }
298
299    impl<E, I, L: InternalLimitConfig> InternalLimitConfig for Configuration<E, I, L> {
300        const LIMIT: Option<usize> = L::LIMIT;
301    }
302}