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