Debian Codegraph @

docs/spec.md

raw
1 # Serialization Specification
2
3 _NOTE_: This specification is primarily defined in the context of Rust, but aims to be implementable across different programming languages.
4
5 ## Definitions
6
7 - **Variant**: A specific constructor or case of an enum type.
8 - **Variant Payload**: The associated data of a specific enum variant.
9 - **Discriminant**: A unique identifier for an enum variant, typically represented as an integer.
10 - **Basic Types**: Primitive types that have a direct, well-defined binary representation.
11
12 ## Endianness
13
14 By default, this serialization format uses little-endian byte order for basic numeric types. This means multi-byte values are encoded with their least significant byte first.
15
16 Endianness can be configured with the following methods, allowing for big-endian serialization when required:
17
18 - [`with_big_endian`](https://docs.rs/bincode/2/bincode/config/struct.Configuration.html#method.with_big_endian)
19 - [`with_little_endian`](https://docs.rs/bincode/2/bincode/config/struct.Configuration.html#method.with_little_endian)
20
21 ### Byte Order Considerations
22
23 - Multi-byte values (integers, floats) are affected by endianness
24 - Single-byte values (u8, i8) are not affected
25 - Struct and collection serialization order is not changed by endianness
26
27 ## Basic Types
28
29 ### Boolean Encoding
30
31 - Encoded as a single byte
32 - `false` is represented by `0`
33 - `true` is represented by `1`
34 - During deserialization, values other than 0 and 1 will result in an error [`DecodeError::InvalidBooleanValue`](https://docs.rs/bincode/2/bincode/error/enum.DecodeError.html#variant.InvalidBooleanValue)
35
36 ### Numeric Types
37
38 - Encoded based on the configured [IntEncoding](#intencoding)
39 - Signed integers use 2's complement representation
40 - Floating point types use IEEE 754-2008 standard
41 - `f32`: 4 bytes (binary32)
42 - `f64`: 8 bytes (binary64)
43
44 #### Floating Point Special Values
45
46 - Subnormal numbers are preserved
47 - Also known as denormalized numbers
48 - Maintain their exact bit representation
49 - `NaN` values are preserved
50 - Both quiet and signaling `NaN` are kept as-is
51 - Bit pattern of `NaN` is maintained exactly
52 - No normalization or transformation of special values occurs
53 - Serialization and deserialization do not alter the bit-level representation
54 - Consistent with IEEE 754-2008 standard for floating-point arithmetic
55
56 ### Character Encoding
57
58 - `char` is encoded as a 32-bit unsigned integer representing its Unicode Scalar Value
59 - Valid Unicode Scalar Value range:
60 - 0x0000 to 0xD7FF (Basic Multilingual Plane)
61 - 0xE000 to 0x10FFFF (Supplementary Planes)
62 - Surrogate code points (0xD800 to 0xDFFF) are not valid
63 - Invalid Unicode characters can be acquired via unsafe code, this is handled as:
64 - during serialization: data is written as-is
65 - during deserialization: an error is raised [`DecodeError::InvalidCharEncoding`](https://docs.rs/bincode/2/bincode/error/enum.DecodeError.html#variant.InvalidCharEncoding)
66 - No additional metadata or encoding scheme beyond the raw code point value
67
68 All tuples have no additional bytes, and are encoded in their specified order, e.g.
69
70 ```rust
71 let tuple = (u32::min_value(), i32::max_value()); // 8 bytes
72 let encoded = bincode::encode_to_vec(tuple, bincode::config::legacy()).unwrap();
73 assert_eq!(encoded.as_slice(), &[
74 0, 0, 0, 0, // 4 bytes for first type: u32
75 255, 255, 255, 127 // 4 bytes for second type: i32
76 ]);
77 ```
78
79 ## IntEncoding
80
81 Bincode currently supports 2 different types of `IntEncoding`. With the default config, `VarintEncoding` is selected.
82
83 ### VarintEncoding
84
85 Encoding an unsigned integer v (of any type excepting u8/i8) works as follows:
86
87 1. If `u < 251`, encode it as a single byte with that value.
88 1. If `251 <= u < 2**16`, encode it as a literal byte 251, followed by a u16 with value `u`.
89 1. If `2**16 <= u < 2**32`, encode it as a literal byte 252, followed by a u32 with value `u`.
90 1. If `2**32 <= u < 2**64`, encode it as a literal byte 253, followed by a u64 with value `u`.
91 1. If `2**64 <= u < 2**128`, encode it as a literal byte 254, followed by a u128 with value `u`.
92
93 `usize` is being encoded/decoded as a `u64` and `isize` is being encoded/decoded as a `i64`.
94
95 See the documentation of [VarintEncoding](https://docs.rs/bincode/2/bincode/config/struct.Configuration.html#method.with_variable_int_encoding) for more information.
96
97 ### FixintEncoding
98
99 - Fixed size integers are encoded directly
100 - Enum discriminants are encoded as u32
101 - Lengths and usize are encoded as u64
102
103 See the documentation of [FixintEncoding](https://docs.rs/bincode/2/bincode/config/struct.Configuration.html#method.with_fixed_int_encoding) for more information.
104
105 ## Enums
106
107 Enums are encoded with their variant first, followed by optionally the variant fields. The variant index is based on the `IntEncoding` during serialization.
108
109 Both named and unnamed fields are serialized with their values only, and therefore encode to the same value.
110
111 ```rust
112 #[derive(bincode::Encode)]
113 pub enum SomeEnum {
114 A,
115 B(u32),
116 C { value: u32 },
117 }
118
119 // SomeEnum::A
120 let encoded = bincode::encode_to_vec(SomeEnum::A, bincode::config::legacy()).unwrap();
121 assert_eq!(encoded.as_slice(), &[
122 0, 0, 0, 0, // first variant, A
123 // no extra bytes because A has no fields
124 ]);
125
126 // SomeEnum::B(0)
127 let encoded = bincode::encode_to_vec(SomeEnum::B(0), bincode::config::legacy()).unwrap();
128 assert_eq!(encoded.as_slice(), &[
129 1, 0, 0, 0, // second variant, B
130 0, 0, 0, 0 // B has 1 unnamed field, which is an u32, so 4 bytes
131 ]);
132
133 // SomeEnum::C { value: 0u32 }
134 let encoded = bincode::encode_to_vec(SomeEnum::C { value: 0u32 }, bincode::config::legacy()).unwrap();
135 assert_eq!(encoded.as_slice(), &[
136 2, 0, 0, 0, // third variant, C
137 0, 0, 0, 0 // C has 1 named field which is a u32, so 4 bytes
138 ]);
139 ```
140
141 ### Options
142
143 `Option<T>` is always serialized using a single byte for the discriminant, even in `Fixint` encoding (which normally uses a `u32` for discriminant).
144
145 ```rust
146 let data: Option<u32> = Some(123);
147 let encoded = bincode::encode_to_vec(data, bincode::config::legacy()).unwrap();
148 assert_eq!(encoded.as_slice(), &[
149 1, 123, 0, 0, 0 // the Some(..) tag is the leading 1
150 ]);
151
152 let data: Option<u32> = None;
153 let encoded = bincode::encode_to_vec(data, bincode::config::legacy()).unwrap();
154 assert_eq!(encoded.as_slice(), &[
155 0 // the None tag is simply 0
156 ]);
157 ```
158
159 # Collections
160
161 ## General Collection Serialization
162
163 Collections are encoded with their length value first, followed by each entry of the collection. The length value is based on the configured `IntEncoding`.
164
165 ### Serialization Considerations
166
167 - Length is always serialized first
168 - Entries are serialized in the order they are returned from the iterator implementation.
169 - Iteration order depends on the collection type
170 - Ordered collections (e.g., `Vec`): Iteration from lowest to highest index
171 - Unordered collections (e.g., `HashMap`): Implementation-defined iteration order
172 - Duplicate keys are not checked in bincode, but may be resulting in an error when decoding a container from a list of pairs.
173
174 ### Handling of Specific Collection Types
175
176 #### Linear Collections (`Vec`, Arrays, etc.)
177
178 - Serialized by iterating from lowest to highest index
179 - Length prefixed
180 - Each item serialized sequentially
181
182 ```rust
183 let list = vec![0u8, 1u8, 2u8];
184 let encoded = bincode::encode_to_vec(list, bincode::config::legacy()).unwrap();
185 assert_eq!(encoded.as_slice(), &[
186 3, 0, 0, 0, 0, 0, 0, 0, // length of 3u64
187 0, // entry 0
188 1, // entry 1
189 2, // entry 2
190 ]);
191 ```
192
193 #### Key-Value Collections (`HashMap`, etc.)
194
195 - Serialized as a sequence of key-value pairs
196 - Iteration order is implementation-defined
197 - Each entry is a tuple of (key, value)
198
199 ### Special Collection Considerations
200
201 - Bincode will serialize the entries based on the iterator order.
202 - Deserialization is deterministic but the collection implementation might not guarantee the same order as serialization.
203
204 **Note**: Fixed-length arrays do not have their length encoded. See [Arrays](#arrays) for details.
205
206 # String and &str
207
208 ## Encoding Principles
209
210 - Strings are encoded as UTF-8 byte sequences
211 - No null terminator is added
212 - No Byte Order Mark (BOM) is written
213 - Unicode non-characters are preserved
214
215 ### Encoding Details
216
217 - Length is encoded first using the configured `IntEncoding`
218 - Raw UTF-8 bytes follow the length
219 - Supports the full range of valid UTF-8 sequences
220 - `U+0000` and other code points can appear freely within the string
221
222 ### Unicode Handling
223
224 - During serialization, the string is encoded as a sequence of the given bytes.
225 - Rust strings are UTF-8 encoded by default, but this is not enforced by bincode
226 - No normalization or transformation of text
227 - If an invalid UTF-8 sequence is encountered during decoding, an [`DecodeError::Utf8`](https://docs.rs/bincode/2/bincode/error/enum.DecodeError.html#variant.Utf8) error is raised
228
229 ```rust
230 let str = "Hello 🌍"; // Mixed ASCII and Unicode
231
232 let encoded = bincode::encode_to_vec(str, bincode::config::legacy()).unwrap();
233 assert_eq!(encoded.as_slice(), &[
234 10, 0, 0, 0, 0, 0, 0, 0, // length of the string, 10 bytes
235 b'H', b'e', b'l', b'l', b'o', b' ', 0xF0, 0x9F, 0x8C, 0x8D // UTF-8 encoded string
236 ]);
237 ```
238
239 ### Comparison with Other Types
240
241 - Treated similarly to `Vec<u8>` in serialization
242 - See [Collections](#collections) for more information about length and entry encoding
243
244 # Arrays
245
246 Array length is never encoded.
247
248 Note that `&[T]` is encoded as a [Collection](#collections).
249
250 ```rust
251 let arr: [u8; 5] = [10, 20, 30, 40, 50];
252 let encoded = bincode::encode_to_vec(arr, bincode::config::legacy()).unwrap();
253 assert_eq!(encoded.as_slice(), &[
254 10, 20, 30, 40, 50, // the bytes
255 ]);
256
257 ```
258
259 This applies to any type `T` that implements `Encode`/`Decode`
260
261 ```rust
262 #[derive(bincode::Encode)]
263 struct Foo {
264 first: u8,
265 second: u8
266 };
267
268 let arr: [Foo; 2] = [
269 Foo {
270 first: 10,
271 second: 20,
272 },
273 Foo {
274 first: 30,
275 second: 40,
276 },
277 ];
278
279 let encoded = bincode::encode_to_vec(&arr, bincode::config::legacy()).unwrap();
280 assert_eq!(encoded.as_slice(), &[
281 10, 20, // First Foo
282 30, 40, // Second Foo
283 ]);
284 ```
285
286 ## TupleEncoding
287
288 Tuple fields are serialized in first-to-last declaration order, with no additional metadata.
289
290 - No length prefix is added
291 - Fields are encoded sequentially
292 - No padding or alignment adjustments are made
293 - Order of serialization is deterministic and matches the tuple's declaration order
294
295 ## StructEncoding
296
297 Struct fields are serialized in first-to-last declaration order, with no metadata representing field names.
298
299 - No length prefix is added
300 - Fields are encoded sequentially
301 - No padding or alignment adjustments are made
302 - Order of serialization is deterministic and matches the struct's field declaration order
303 - Both named and unnamed fields are serialized identically
304
305 ## EnumEncoding
306
307 Enum variants are encoded with a discriminant followed by optional variant payload.
308
309 ### Discriminant Allocation
310
311 - Discriminants are automatically assigned by the derive macro in declaration order
312 - First variant starts at 0
313 - Subsequent variants increment by 1
314 - Explicit discriminant indices are currently not supported
315 - Discriminant is always represented as a `u32` during serialization. See [Discriminant Representation](#discriminant-representation) for more details.
316 - Maintains the original enum variant semantics during encoding
317
318 ### Variant Payload Encoding
319
320 - Tuple variants: Fields serialized in declaration order
321 - Struct variants: Fields serialized in declaration order
322 - Unit variants: No additional data encoded
323
324 ### Discriminant Representation
325
326 - Always encoded as a `u32`
327 - Encoding method depends on the configured `IntEncoding`
328 - `VarintEncoding`: Variable-length encoding
329 - `FixintEncoding`: Fixed 4-byte representation
330
331 ### Handling of Variant Payloads
332
333 - Payload is serialized immediately after the discriminant
334 - No additional metadata about field names or types
335 - Payload structure matches the variant's definition