bincode-next 3.1.2

A compact, ultra-fast binary serialization format for Rust, optimized for networking and storage!
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! This module contains writer-based structs and traits.
//!
//! Because `std::io::Write` is only limited to `std` and not `core`, we provide our own [Writer].
#![allow(unsafe_code)]

use crate::error::EncodeError;

#[cfg(feature = "alloc")]
impl Writer for crate::alloc::vec::Vec<u8> {
    #[inline(always)]
    fn write(
        &mut self,
        bytes: &[u8],
    ) -> Result<(), EncodeError> {
        self.extend_from_slice(bytes);
        Ok(())
    }

    #[inline(always)]
    fn write_u8(
        &mut self,
        value: u8,
    ) -> Result<(), EncodeError> {
        self.push(value);
        Ok(())
    }

    #[inline(always)]
    fn write_u16(
        &mut self,
        value: u16,
    ) -> Result<(), EncodeError> {
        self.reserve(2);
        unsafe {
            let len = self.len();
            core::ptr::write_unaligned(self.as_mut_ptr().add(len).cast::<u16>(), value);
            self.set_len(len + 2);
        }
        Ok(())
    }

    #[inline(always)]
    fn write_u32(
        &mut self,
        value: u32,
    ) -> Result<(), EncodeError> {
        self.reserve(4);
        unsafe {
            let len = self.len();
            core::ptr::write_unaligned(self.as_mut_ptr().add(len).cast::<u32>(), value);
            self.set_len(len + 4);
        }
        Ok(())
    }

    #[inline(always)]
    fn write_u64(
        &mut self,
        value: u64,
    ) -> Result<(), EncodeError> {
        self.reserve(8);
        unsafe {
            let len = self.len();
            core::ptr::write_unaligned(self.as_mut_ptr().add(len).cast::<u64>(), value);
            self.set_len(len + 8);
        }
        Ok(())
    }

    #[inline(always)]
    fn write_u128(
        &mut self,
        value: u128,
    ) -> Result<(), EncodeError> {
        self.reserve(16);
        unsafe {
            let len = self.len();
            core::ptr::write_unaligned(self.as_mut_ptr().add(len).cast::<u128>(), value);
            self.set_len(len + 16);
        }
        Ok(())
    }
}

/// Trait that indicates that a struct can be used as a destination to encode data too. This is used by [Encode]
///
/// [Encode]: ../trait.Encode.html
pub trait Writer {
    /// Write `bytes` to the underlying writer. Exactly `bytes.len()` bytes must be written, or else an error should be returned.
    ///
    /// # Errors
    ///
    /// Returns `EncodeError::UnexpectedEnd` if the writer does not have enough space.
    fn write(
        &mut self,
        bytes: &[u8],
    ) -> Result<(), EncodeError>;

    /// Write a single byte to the underlying writer.
    ///
    /// # Errors
    ///
    /// Returns `EncodeError::UnexpectedEnd` if the writer does not have enough space.
    #[inline(always)]
    fn write_u8(
        &mut self,
        value: u8,
    ) -> Result<(), EncodeError> {
        self.write(&[value])
    }

    /// Write a `u16` to the underlying writer.
    ///
    /// # Errors
    ///
    /// Returns `EncodeError::UnexpectedEnd` if the writer does not have enough space.
    #[inline(always)]
    fn write_u16(
        &mut self,
        value: u16,
    ) -> Result<(), EncodeError> {
        self.write(&value.to_ne_bytes())
    }

    /// Write a `u32` to the underlying writer.
    ///
    /// # Errors
    ///
    /// Returns `EncodeError::UnexpectedEnd` if the writer does not have enough space.
    #[inline(always)]
    fn write_u32(
        &mut self,
        value: u32,
    ) -> Result<(), EncodeError> {
        self.write(&value.to_ne_bytes())
    }

    /// Write a `u64` to the underlying writer.
    ///
    /// # Errors
    ///
    /// Returns `EncodeError::UnexpectedEnd` if the writer does not have enough space.
    #[inline(always)]
    fn write_u64(
        &mut self,
        value: u64,
    ) -> Result<(), EncodeError> {
        self.write(&value.to_ne_bytes())
    }

    /// Write a `u128` to the underlying writer.
    ///
    /// # Errors
    ///
    /// Returns `EncodeError::UnexpectedEnd` if the writer does not have enough space.
    #[inline(always)]
    fn write_u128(
        &mut self,
        value: u128,
    ) -> Result<(), EncodeError> {
        self.write(&value.to_ne_bytes())
    }
}

impl<T: Writer> Writer for &mut T {
    #[inline(always)]
    fn write(
        &mut self,
        bytes: &[u8],
    ) -> Result<(), EncodeError> {
        (**self).write(bytes)
    }

    #[inline(always)]
    fn write_u8(
        &mut self,
        value: u8,
    ) -> Result<(), EncodeError> {
        (**self).write_u8(value)
    }

    #[inline(always)]
    fn write_u16(
        &mut self,
        value: u16,
    ) -> Result<(), EncodeError> {
        (**self).write_u16(value)
    }

    #[inline(always)]
    fn write_u32(
        &mut self,
        value: u32,
    ) -> Result<(), EncodeError> {
        (**self).write_u32(value)
    }

    #[inline(always)]
    fn write_u64(
        &mut self,
        value: u64,
    ) -> Result<(), EncodeError> {
        (**self).write_u64(value)
    }

    #[inline(always)]
    fn write_u128(
        &mut self,
        value: u128,
    ) -> Result<(), EncodeError> {
        (**self).write_u128(value)
    }
}

/// A helper struct that implements `Writer` for a `&[u8]` slice.
///
/// ```
/// use bincode_next::enc::write::SliceWriter;
/// use bincode_next::enc::write::Writer;
///
/// let destination = &mut [0u8; 100];
/// let mut writer = SliceWriter::new(destination);
/// writer.write(&[1, 2, 3, 4, 5]).unwrap();
///
/// assert_eq!(writer.bytes_written(), 5);
/// assert_eq!(destination[0..6], [1, 2, 3, 4, 5, 0]);
/// ```
pub struct SliceWriter<'storage> {
    slice: &'storage mut [u8],
    original_length: usize,
}

impl<'storage> SliceWriter<'storage> {
    /// Create a new instance of `SliceWriter` with the given byte array.
    pub const fn new(bytes: &'storage mut [u8]) -> Self {
        let original = bytes.len();
        Self {
            slice: bytes,
            original_length: original,
        }
    }

    /// Return the amount of bytes written so far.
    #[must_use]
    pub const fn bytes_written(&self) -> usize {
        self.original_length - self.slice.len()
    }
}

impl Writer for SliceWriter<'_> {
    #[inline(always)]
    fn write(
        &mut self,
        bytes: &[u8],
    ) -> Result<(), EncodeError> {
        if bytes.len() > self.slice.len() {
            return crate::error::cold_encode_error_unexpected_end();
        }
        // SAFETY: `bytes.len() <= self.slice.len()` is checked above.
        // `copy_nonoverlapping` is safe since the pointers won't overlap and bounds are exact.
        // Advancing the pointer by `bytes.len()` is safe for the same reason.
        unsafe {
            core::ptr::copy_nonoverlapping(bytes.as_ptr(), self.slice.as_mut_ptr(), bytes.len());
            let ptr = self.slice.as_mut_ptr().add(bytes.len());
            let len = self.slice.len() - bytes.len();
            self.slice = core::slice::from_raw_parts_mut(ptr, len);
        }

        Ok(())
    }

    #[inline(always)]
    fn write_u8(
        &mut self,
        value: u8,
    ) -> Result<(), EncodeError> {
        if self.slice.is_empty() {
            return crate::error::cold_encode_error_unexpected_end();
        }
        // SAFETY: `!self.slice.is_empty()` is checked above.
        unsafe {
            *self.slice.as_mut_ptr() = value;
            let ptr = self.slice.as_mut_ptr().add(1);
            let len = self.slice.len() - 1;
            self.slice = core::slice::from_raw_parts_mut(ptr, len);
        }

        Ok(())
    }

    #[inline(always)]
    fn write_u16(
        &mut self,
        value: u16,
    ) -> Result<(), EncodeError> {
        if self.slice.len() < 2 {
            return crate::error::cold_encode_error_unexpected_end();
        }
        // SAFETY: `self.slice.len() < 2` is checked above.
        unsafe {
            core::ptr::write_unaligned(self.slice.as_mut_ptr().cast::<u16>(), value);
            let ptr = self.slice.as_mut_ptr().add(2);
            let len = self.slice.len() - 2;
            self.slice = core::slice::from_raw_parts_mut(ptr, len);
        }

        Ok(())
    }

    #[inline(always)]
    fn write_u32(
        &mut self,
        value: u32,
    ) -> Result<(), EncodeError> {
        if self.slice.len() < 4 {
            return crate::error::cold_encode_error_unexpected_end();
        }
        // SAFETY: `self.slice.len() < 4` is checked above.
        unsafe {
            core::ptr::write_unaligned(self.slice.as_mut_ptr().cast::<u32>(), value);
            let ptr = self.slice.as_mut_ptr().add(4);
            let len = self.slice.len() - 4;
            self.slice = core::slice::from_raw_parts_mut(ptr, len);
        }

        Ok(())
    }

    #[inline(always)]
    fn write_u64(
        &mut self,
        value: u64,
    ) -> Result<(), EncodeError> {
        if self.slice.len() < 8 {
            return crate::error::cold_encode_error_unexpected_end();
        }
        // SAFETY: `self.slice.len() < 8` is checked above.
        unsafe {
            core::ptr::write_unaligned(self.slice.as_mut_ptr().cast::<u64>(), value);
            let ptr = self.slice.as_mut_ptr().add(8);
            let len = self.slice.len() - 8;
            self.slice = core::slice::from_raw_parts_mut(ptr, len);
        }

        Ok(())
    }

    #[inline(always)]
    fn write_u128(
        &mut self,
        value: u128,
    ) -> Result<(), EncodeError> {
        if self.slice.len() < 16 {
            return crate::error::cold_encode_error_unexpected_end();
        }
        // SAFETY: `self.slice.len() < 16` is checked above.
        unsafe {
            core::ptr::write_unaligned(self.slice.as_mut_ptr().cast::<u128>(), value);
            let ptr = self.slice.as_mut_ptr().add(16);
            let len = self.slice.len() - 16;
            self.slice = core::slice::from_raw_parts_mut(ptr, len);
        }

        Ok(())
    }
}

/// A writer that counts how many bytes were written. This is useful for e.g. pre-allocating buffers before writing to them.
#[derive(Default)]
pub struct SizeWriter {
    /// the amount of bytes that were written so far
    pub bytes_written: usize,
}
impl Writer for SizeWriter {
    #[inline(always)]
    fn write(
        &mut self,
        bytes: &[u8],
    ) -> Result<(), EncodeError> {
        self.bytes_written += bytes.len();

        Ok(())
    }

    #[inline(always)]
    fn write_u8(
        &mut self,
        _: u8,
    ) -> Result<(), EncodeError> {
        self.bytes_written += 1;

        Ok(())
    }

    #[inline(always)]
    fn write_u16(
        &mut self,
        _: u16,
    ) -> Result<(), EncodeError> {
        self.bytes_written += 2;

        Ok(())
    }

    #[inline(always)]
    fn write_u32(
        &mut self,
        _: u32,
    ) -> Result<(), EncodeError> {
        self.bytes_written += 4;

        Ok(())
    }

    #[inline(always)]
    fn write_u64(
        &mut self,
        _: u64,
    ) -> Result<(), EncodeError> {
        self.bytes_written += 8;

        Ok(())
    }

    #[inline(always)]
    fn write_u128(
        &mut self,
        _: u128,
    ) -> Result<(), EncodeError> {
        self.bytes_written += 16;

        Ok(())
    }
}