wincode 0.5.3

Fast bincode de/serialization with placement initialization
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
use {
    super::*,
    core::{marker::PhantomData, ptr::copy_nonoverlapping},
};

/// Split the given mutable slice by `len` bytes, advancing the slice by `len` bytes, or
/// returning an error if the input slice does not have at least `len` bytes remaining.
#[inline(always)]
fn advance_slice_mut_checked<'a, T>(input: &mut &'a mut [T], len: usize) -> Option<&'a mut [T]> {
    let (dst, rest) = mem::take(input).split_at_mut_checked(len)?;
    *input = rest;
    Some(dst)
}

/// Split the given mutable slice by `len` bytes, advancing the slice by `len` bytes.
///
/// # Safety
///
/// Calling this method with an out-of-bounds `len` is undefined behavior
/// even if the resulting reference is not used. The caller has to ensure that
/// `0 <= len <= self.len()`.
#[inline(always)]
unsafe fn advance_slice_mut_unchecked<'a, T>(input: &mut &'a mut [T], len: usize) -> &'a mut [T] {
    let (dst, rest) = unsafe { mem::take(input).split_at_mut_unchecked(len) };
    *input = rest;
    dst
}

/// Split the given slice by `len` bytes, advancing the slice by `len` bytes, or
/// returning an error if the input slice does not have at least `len` bytes remaining.
#[inline(always)]
fn advance_slice_checked<'a, T>(input: &mut &'a [T], len: usize) -> Option<&'a [T]> {
    let (dst, rest) = input.split_at_checked(len)?;
    *input = rest;
    Some(dst)
}

/// Split the given slice by `len` bytes, advancing the slice by `len` bytes.
///
/// # Safety
///
/// Calling this method with an out-of-bounds `len` is undefined behavior
/// even if the resulting reference is not used. The caller has to ensure that
/// `0 <= len <= self.len()`.
#[inline(always)]
unsafe fn advance_slice_unchecked<'a, T>(input: &mut &'a [T], len: usize) -> &'a [T] {
    let (dst, rest) = unsafe { input.split_at_unchecked(len) };
    *input = rest;
    dst
}

/// Implementation of [`Reader`] over a slice that does not perform any bounds checks.
///
/// This implementation inherits the lifetime of the underlying slice, and can be used
/// for zero-copy [`Reader`] implementations.
pub struct SliceUnchecked<'a, T> {
    buf: &'a [T],
}

impl<'a, T> SliceUnchecked<'a, T> {
    /// Create a new [`SliceUnchecked`] from the given slice.
    ///
    /// # Safety
    ///
    /// [`SliceUnchecked`]'s implementation of [`Reader`] will not perform any
    /// bounds checks on the slice. It is up to the caller to ensure that any
    /// [`Reader`] operations performed are within the bounds of the slice.
    pub const unsafe fn new(buf: &'a [T]) -> Self {
        Self { buf }
    }
}

impl<'a> Reader<'a> for SliceUnchecked<'a, u8> {
    const BORROW_KINDS: u8 = BorrowKind::Backing.mask() | BorrowKind::CallSite.mask();

    #[inline]
    fn copy_into_slice(&mut self, buf: &mut [MaybeUninit<u8>]) -> ReadResult<()> {
        // SAFETY: by constructing `SliceUnchecked`, caller guarantees
        // they will read within the bounds of the slice.
        let chunk = unsafe { advance_slice_unchecked(&mut self.buf, buf.len()) };
        // SAFETY:
        // -  Given the previous assumption that the caller guarantees the underlying
        //    slice in bounds for the next `buf.len()` bytes, we assume that `chunk` is a valid,
        //    in bounds, `buf.len()` bytes slice.
        // - Given Rust's aliasing rules, we can assume that `buf` does not overlap with the internal buffer.
        unsafe { copy_nonoverlapping(chunk.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
        Ok(())
    }

    #[inline(always)]
    fn take_array<const N: usize>(&mut self) -> ReadResult<[u8; N]> {
        // SAFETY: by constructing `SliceUnchecked`, caller guarantees
        // they will read within the bounds of the slice.
        let chunk = unsafe { advance_slice_unchecked(&mut self.buf, N) };
        // SAFETY: given the previous assumption that the caller guarantees the underlying
        // slice in bounds for the next `N` bytes, we assume that `chunk` is a valid
        // `&[u8; N]` slice.
        Ok(unsafe { *(chunk.as_ptr().cast::<[u8; N]>()) })
    }

    #[inline]
    fn take_borrowed(&mut self, len: usize) -> ReadResult<&'a [u8]> {
        // SAFETY: by constructing `SliceUnchecked`, caller guarantees
        // they will read within the bounds of the slice.
        let chunk = unsafe { advance_slice_unchecked(&mut self.buf, len) };
        Ok(chunk)
    }

    #[inline]
    fn take_scoped(&mut self, len: usize) -> ReadResult<&[u8]> {
        self.take_borrowed(len)
    }
}

/// Implementation of [`Reader`] and [`Writer`] over a slice that does not perform any bounds checks.
///
/// This implementation inherits the lifetime of the underlying slice, and can be used
/// for zero-copy [`Reader`] implementations.
pub struct SliceMutUnchecked<'a, T> {
    buf: &'a mut [T],
}

#[cfg(test)]
impl<T> core::ops::Deref for SliceMutUnchecked<'_, T> {
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        self.buf
    }
}

impl<'a, T> SliceMutUnchecked<'a, T> {
    /// Create a new [`SliceMutUnchecked`] from the given slice.
    ///
    /// # Safety
    ///
    /// [`SliceMutUnchecked`]'s implementation of [`Reader`] and [`Writer`] will
    /// not perform any bounds checks on the slice. It is up to the caller to
    /// ensure that any [`Reader`] or [`Writer`] operations performed are within
    /// the bounds of the slice.
    ///
    /// ## Reading
    ///
    /// - The total number of bytes accessed/consumed must be within
    ///   the bounds of the slice.
    ///
    /// ## Writing
    ///
    /// - All writes performed must stay within the bounds of the slice.
    /// - It is permitted to overwrite the same bytes multiple times.
    pub const unsafe fn new(buf: &'a mut [T]) -> Self {
        Self { buf }
    }
}

impl<'a> Reader<'a> for SliceMutUnchecked<'a, u8> {
    const BORROW_KINDS: u8 =
        BorrowKind::Backing.mask() | BorrowKind::BackingMut.mask() | BorrowKind::CallSite.mask();

    #[inline]
    fn copy_into_slice(&mut self, buf: &mut [MaybeUninit<u8>]) -> ReadResult<()> {
        // SAFETY: by constructing `SliceMutUnchecked`, caller guarantees
        // they will read within the bounds of the slice.
        let chunk = unsafe { advance_slice_mut_unchecked(&mut self.buf, buf.len()) };
        // SAFETY:
        // -  Given the previous assumption that the caller guarantees the underlying
        //    slice in bounds for the next `buf.len()` bytes, we assume that `chunk` is a valid,
        //    in bounds, `buf.len()` bytes slice.
        // - Given Rust's aliasing rules, we can assume that `buf` does not overlap with the internal buffer.
        unsafe { copy_nonoverlapping(chunk.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
        Ok(())
    }

    #[inline(always)]
    fn take_array<const N: usize>(&mut self) -> ReadResult<[u8; N]> {
        // SAFETY: by constructing `SliceMutUnchecked`, caller guarantees
        // they will read within the bounds of the slice.
        let chunk = unsafe { advance_slice_mut_unchecked(&mut self.buf, N) };
        // SAFETY: given the previous assumption that the caller guarantees the underlying
        // slice in bounds for the next `N` bytes, we assume that `chunk` is a valid
        // `&[u8; N]` slice.
        Ok(unsafe { *(chunk.as_ptr().cast::<[u8; N]>()) })
    }

    #[inline]
    fn take_borrowed_mut(&mut self, len: usize) -> ReadResult<&'a mut [u8]> {
        // SAFETY: by constructing `SliceMutUnchecked`, caller guarantees
        // they will read within the bounds of the slice.
        Ok(unsafe { advance_slice_mut_unchecked(&mut self.buf, len) })
    }

    #[inline]
    fn take_borrowed(&mut self, len: usize) -> ReadResult<&'a [u8]> {
        self.take_borrowed_mut(len).map(|s| &*s)
    }

    #[inline]
    fn take_scoped(&mut self, len: usize) -> ReadResult<&[u8]> {
        self.take_borrowed(len)
    }
}

/// Implementation of [`Reader`] over a slice that does not perform any bounds checks.
///
/// This implementation inherits the lifetime of its lexical scope, and can be used
/// for non-borrowing [`Reader`] implementations.
pub struct SliceScopedUnchecked<'a, 'b, T> {
    inner: SliceUnchecked<'b, T>,
    _marker: PhantomData<&'a [T]>,
}

impl<'b, T> SliceScopedUnchecked<'_, 'b, T> {
    /// Create a new [`SliceScopedUnchecked`] from the given slice.
    ///
    /// # Safety
    ///
    /// [`SliceScopedUnchecked`]'s implementation of [`Reader`] will not perform any
    /// bounds checks on the slice. It is up to the caller to ensure that any
    /// [`Reader`] operations performed are within the bounds of the slice.
    #[inline(always)]
    pub const unsafe fn new(buf: &'b [T]) -> Self {
        Self {
            inner: unsafe { SliceUnchecked::new(buf) },
            _marker: PhantomData,
        }
    }
}

impl<'a> Reader<'a> for SliceScopedUnchecked<'a, '_, u8> {
    const BORROW_KINDS: u8 = BorrowKind::CallSite.mask();

    #[inline(always)]
    fn copy_into_slice(&mut self, buf: &mut [MaybeUninit<u8>]) -> ReadResult<()> {
        self.inner.copy_into_slice(buf)
    }

    #[inline(always)]
    fn take_array<const N: usize>(&mut self) -> ReadResult<[u8; N]> {
        self.inner.take_array()
    }

    #[inline(always)]
    fn take_scoped(&mut self, len: usize) -> ReadResult<&[u8]> {
        self.inner.take_scoped(len)
    }
}

impl<'a> Reader<'a> for &'a [u8] {
    const BORROW_KINDS: u8 = BorrowKind::Backing.mask() | BorrowKind::CallSite.mask();

    #[inline]
    fn take_borrowed(&mut self, len: usize) -> ReadResult<&'a [u8]> {
        let Some(src) = advance_slice_checked(self, len) else {
            return Err(read_size_limit(len));
        };
        Ok(src)
    }

    #[inline(always)]
    fn take_scoped(&mut self, len: usize) -> ReadResult<&[u8]> {
        self.take_borrowed(len)
    }

    #[inline]
    fn copy_into_slice(&mut self, dst: &mut [MaybeUninit<u8>]) -> ReadResult<()> {
        let Some(src) = advance_slice_checked(self, dst.len()) else {
            return Err(read_size_limit(dst.len()));
        };
        // SAFETY:
        // - `advance_slice_checked` guarantees that `src` is exactly `dst.len()` bytes.
        // - Given Rust's aliasing rules, we can assume that `dst` does not overlap
        //   with the internal buffer.
        unsafe { copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr().cast(), dst.len()) };
        Ok(())
    }

    #[inline(always)]
    fn take_array<const N: usize>(&mut self) -> ReadResult<[u8; N]> {
        let Some((src, rest)) = self.split_first_chunk() else {
            return Err(read_size_limit(N));
        };
        *self = rest;
        Ok(*src)
    }

    #[inline(always)]
    unsafe fn as_trusted_for(&mut self, n_bytes: usize) -> ReadResult<impl Reader<'a>> {
        let Some(window) = advance_slice_checked(self, n_bytes) else {
            return Err(read_size_limit(n_bytes));
        };
        // SAFETY: by calling `as_trusted_for`, caller guarantees they
        // will will not read beyond the bounds of the slice, `n_bytes`.
        Ok(unsafe { SliceUnchecked::new(window) })
    }
}

impl<'a> Reader<'a> for &'a mut [u8] {
    const BORROW_KINDS: u8 =
        BorrowKind::Backing.mask() | BorrowKind::BackingMut.mask() | BorrowKind::CallSite.mask();

    #[inline(always)]
    unsafe fn as_trusted_for(&mut self, n_bytes: usize) -> ReadResult<impl Reader<'a>> {
        let Some(window) = advance_slice_mut_checked(self, n_bytes) else {
            return Err(read_size_limit(n_bytes));
        };
        // SAFETY: by calling `as_trusted_for`, caller guarantees they
        // will will not read beyond the bounds of the slice, `n_bytes`.
        Ok(unsafe { SliceMutUnchecked::new(window) })
    }

    #[inline]
    fn take_borrowed_mut(&mut self, len: usize) -> ReadResult<&'a mut [u8]> {
        let Some(src) = advance_slice_mut_checked(self, len) else {
            return Err(read_size_limit(len));
        };
        Ok(src)
    }

    #[inline]
    fn take_borrowed(&mut self, len: usize) -> ReadResult<&'a [u8]> {
        self.take_borrowed_mut(len).map(|s| &*s)
    }

    #[inline]
    fn take_scoped(&mut self, len: usize) -> ReadResult<&[u8]> {
        self.take_borrowed(len)
    }

    #[inline]
    fn copy_into_slice(&mut self, dst: &mut [MaybeUninit<u8>]) -> ReadResult<()> {
        let src = self.take_borrowed(dst.len())?;
        // SAFETY:
        // - `borrow_exact` guarantees that `src` is exactly dst.len() bytes.
        // - Given Rust's aliasing rules, we can assume that `buf` does not overlap with the internal buffer.
        unsafe { copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr().cast(), dst.len()) }
        Ok(())
    }

    #[inline(always)]
    fn take_array<const N: usize>(&mut self) -> ReadResult<[u8; N]> {
        let Some((src, rest)) = mem::take(self).split_first_chunk_mut() else {
            return Err(read_size_limit(N));
        };
        *self = rest;
        Ok(*src)
    }
}

impl Writer for SliceMutUnchecked<'_, u8> {
    #[inline(always)]
    fn write(&mut self, src: &[u8]) -> WriteResult<()> {
        // SAFETY: by constructing `SliceMutUnchecked`, caller guarantees
        // they will write within the bounds of the slice.
        let dst = unsafe { advance_slice_mut_unchecked(&mut self.buf, src.len()) };
        // SAFETY:
        // -  Given the previous assumption that the caller guarantees the underlying
        //    slice in bounds for the next `buf.len()` bytes, we assume that `dst` is a valid,
        //    in bounds, `src.len()` bytes slice.
        // - Given Rust's aliasing rules, we can assume that `src` does not overlap with the internal buffer.
        unsafe { copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr().cast(), src.len()) }
        Ok(())
    }
}

impl Writer for SliceMutUnchecked<'_, MaybeUninit<u8>> {
    #[inline(always)]
    fn write(&mut self, src: &[u8]) -> WriteResult<()> {
        // SAFETY: by constructing `SliceMutUnchecked`, caller guarantees
        // they will write within the bounds of the slice.
        let dst = unsafe { advance_slice_mut_unchecked(&mut self.buf, src.len()) };
        // SAFETY:
        // -  Given the previous assumption that the caller guarantees the underlying
        //    slice in bounds for the next `buf.len()` bytes, we assume that `dst` is a valid,
        //    in bounds, `src.len()` bytes slice.
        // - Given Rust's aliasing rules, we can assume that `src` does not overlap with the internal buffer.
        unsafe { copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr().cast(), src.len()) }
        Ok(())
    }
}

impl Writer for &mut [MaybeUninit<u8>] {
    #[inline(always)]
    unsafe fn as_trusted_for(&mut self, n_bytes: usize) -> WriteResult<impl Writer> {
        let Some(window) = advance_slice_mut_checked(self, n_bytes) else {
            return Err(write_size_limit(n_bytes));
        };
        // SAFETY: by calling `as_trusted_for`, caller guarantees they
        // will fully initialize `n_bytes` of memory and will not write
        // beyond the bounds of the slice.
        Ok(unsafe { SliceMutUnchecked::new(window) })
    }

    #[inline(always)]
    fn write(&mut self, src: &[u8]) -> WriteResult<()> {
        let Some(dst) = advance_slice_mut_checked(self, src.len()) else {
            return Err(write_size_limit(src.len()));
        };

        // SAFETY: `advance_slice_mut_checked` guarantees that `dst` is exactly `src.len()` bytes.
        unsafe { copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr().cast(), src.len()) }
        Ok(())
    }
}

impl Writer for &mut [u8] {
    #[inline(always)]
    unsafe fn as_trusted_for(&mut self, n_bytes: usize) -> WriteResult<impl Writer> {
        let Some(window) = advance_slice_mut_checked(self, n_bytes) else {
            return Err(write_size_limit(n_bytes));
        };
        // SAFETY: by calling `as_trusted_for`, caller guarantees they
        // will fully initialize `n_bytes` of memory and will not write
        // beyond the bounds of the slice.
        Ok(unsafe { SliceMutUnchecked::new(window) })
    }

    #[inline]
    fn write(&mut self, src: &[u8]) -> WriteResult<()> {
        let Some(dst) = advance_slice_mut_checked(self, src.len()) else {
            return Err(write_size_limit(src.len()));
        };

        // SAFETY:
        // - `advance_slice_mut_checked` guarantees that `dst` is exactly `src.len()` bytes.
        // - Given Rust's aliasing rules, we can assume that `src` does not overlap
        //   with the internal buffer.
        unsafe { copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr().cast(), src.len()) }
        Ok(())
    }
}

#[cfg(all(test, feature = "alloc"))]
mod tests {
    #![allow(clippy::arithmetic_side_effects)]
    use {super::*, crate::proptest_config::proptest_cfg, alloc::vec::Vec, proptest::prelude::*};

    /// Execute the given block with supported readers.
    macro_rules! with_readers {
        ($bytes:expr, |$reader:ident| $body:block) => {{
            {
                let mut $reader = $bytes.as_slice();
                $body
            }
            {
                let mut $reader = unsafe { SliceUnchecked::new($bytes) };
                $body
            }
            {
                let mut $reader = Cursor::new($bytes);
                $body
            }
            #[cfg(feature = "std")]
            {
                let mut $reader = std::io::Cursor::new($bytes);
                $body
            }
        }};
    }

    /// Execute the given block with readers that will bounds check (and thus not panic).
    macro_rules! with_untrusted_readers {
        ($bytes:expr, |$reader:ident| $body:block) => {{
            {
                let mut $reader = $bytes.as_slice();
                $body
            }
            {
                let mut $reader = Cursor::new($bytes);
                $body
            }
            #[cfg(feature = "std")]
            {
                let mut $reader = std::io::Cursor::new($bytes);
                $body
            }
        }};
    }

    /// Execute the given block with slice reference writer and trusted slice writer for the given buffer.
    macro_rules! with_writers {
        ($buffer:expr, |$writer:ident| $body:block) => {{
            {
                let mut $writer = $buffer.spare_capacity_mut();
                $body
                $buffer.clear();
            }
            {
                let mut $writer = unsafe { SliceMutUnchecked::new($buffer.spare_capacity_mut()) };
                $body
                $buffer.clear();
            }
            {
                let _capacity = $buffer.capacity();
                $buffer.resize(_capacity, 0);
                let mut $writer = $buffer.as_mut_slice();
                $body
                $buffer.clear();
            }
        }};
    }

    // Execute the given block with slice writer of the given preallocated buffer.
    macro_rules! with_known_len_writers {
        ($buffer:expr, |$writer:ident| $body_write:block, $body_check:expr) => {{
            let capacity = $buffer.capacity();
            {
                $buffer.resize(capacity, 0);
                $buffer.fill(0);
                let mut $writer = $buffer.as_mut_slice();
                $body_write
                $body_check;
                $buffer.clear();
            }
            {
                $buffer.fill(0);
                $buffer.clear();
                let mut $writer = $buffer.spare_capacity_mut();
                $body_write
                unsafe { $buffer.set_len(capacity) }
                $body_check;
            }
        }};
    }

    proptest! {
        #![proptest_config(proptest_cfg())]

        #[test]
        fn test_reader_copy_into_slice(bytes in any::<Vec<u8>>()) {
            with_readers!(&bytes, |reader| {
                let mut vec = Vec::with_capacity(bytes.len());
                let half = bytes.len() / 2;
                let dst = vec.spare_capacity_mut();
                reader.copy_into_slice(&mut dst[..half]).unwrap();
                unsafe { reader.as_trusted_for(bytes.len() - half) }
                    .unwrap()
                    .copy_into_slice(&mut dst[half..])
                    .unwrap();
                unsafe { vec.set_len(bytes.len()) };
                prop_assert_eq!(&vec, &bytes);
            });
        }

        #[test]
        fn test_reader_take_scoped(bytes in any::<Vec<u8>>()) {
            with_readers!(&bytes, |reader| {
                let read = reader.take_scoped(bytes.len()).unwrap();
                prop_assert_eq!(&read, &bytes);
            });
        }

        #[test]
        fn reader_take_scoped_input_too_large(bytes in any::<Vec<u8>>()) {
            with_untrusted_readers!(&bytes, |reader| {
                prop_assert!(matches!(reader.take_scoped(bytes.len() + 1), Err(ReadError::ReadSizeLimit(x)) if x == bytes.len() + 1));
            });
        }

        #[test]
        fn test_reader_copy_into_slice_input_too_large(bytes in any::<Vec<u8>>()) {
            with_untrusted_readers!(&bytes, |reader| {
                let mut vec = Vec::with_capacity(bytes.len() + 1);
                let dst = vec.spare_capacity_mut();
                prop_assert!(matches!(reader.copy_into_slice(dst), Err(ReadError::ReadSizeLimit(x)) if x == bytes.len() + 1));
            });
        }

        #[test]
        fn test_reader_copy_into_t(ints in proptest::collection::vec(any::<u64>(), 0..=100)) {
            let bytes = ints.iter().flat_map(|int| int.to_le_bytes()).collect::<Vec<u8>>();
            with_readers!(&bytes, |reader| {
                for int in &ints {
                    let mut val = MaybeUninit::<u64>::uninit();
                    unsafe { reader.copy_into_t(&mut val).unwrap() };
                    unsafe { prop_assert_eq!(val.assume_init(), *int) };
                }
            });
        }

        #[test]
        fn test_reader_copy_into_slice_t(ints in proptest::collection::vec(any::<u64>(), 0..=100)) {
            let bytes = ints.iter().flat_map(|int| int.to_le_bytes()).collect::<Vec<u8>>();
            with_readers!(&bytes, |reader| {
                let mut vals: Vec<u64> = Vec::with_capacity(ints.len());
                let dst = vals.spare_capacity_mut();
                unsafe { reader.copy_into_slice_t(dst).unwrap() };
                unsafe { vals.set_len(ints.len()) };
                prop_assert_eq!(&vals, &ints);
            });
        }

        #[test]
        fn test_writer_write(bytes in any::<Vec<u8>>()) {
            let capacity = bytes.len();
            let mut buffer = Vec::with_capacity(capacity);
            with_writers!(&mut buffer, |writer| {
                writer.write(&bytes).unwrap();
                let written = capacity - writer.len();
                unsafe { buffer.set_len(written) };
                prop_assert_eq!(&buffer, &bytes);
            });

            with_known_len_writers!(&mut buffer, |writer| {
                writer.write(&bytes).unwrap();
            }, prop_assert_eq!(&buffer, &bytes));
        }

        #[test]
        fn test_writer_write_input_too_large(bytes in proptest::collection::vec(any::<u8>(), 1..=100)) {
            let mut buffer = Vec::with_capacity(bytes.len() - 1);
            let mut writer = buffer.spare_capacity_mut();
            prop_assert!(matches!(writer.write(&bytes), Err(WriteError::WriteSizeLimit(x)) if x == bytes.len()));
        }

        #[test]
        fn test_writer_write_t(int in any::<u64>()) {
            let capacity = 8;
            let mut buffer = Vec::with_capacity(capacity);
            with_writers!(&mut buffer, |writer| {
                unsafe { writer.write_t(&int).unwrap() };
                let written = capacity - writer.len();
                unsafe { buffer.set_len(written) };
                prop_assert_eq!(&buffer, &int.to_le_bytes());
            });

            with_known_len_writers!(&mut buffer, |writer| {
                unsafe { writer.write_t(&int).unwrap() };
            }, prop_assert_eq!(&buffer, &int.to_le_bytes()));
        }

        #[test]
        fn test_writer_write_slice_t(ints in proptest::collection::vec(any::<u64>(), 0..=100)) {
            let bytes = ints.iter().flat_map(|int| int.to_le_bytes()).collect::<Vec<u8>>();
            let capacity = bytes.len();
            let mut buffer = Vec::with_capacity(capacity);
            with_writers!(&mut buffer, |writer| {
                unsafe { writer.write_slice_t(&ints).unwrap() };
                let written = capacity - writer.len();
                unsafe { buffer.set_len(written) };
                prop_assert_eq!(&buffer, &bytes);
            });

            with_known_len_writers!(&mut buffer, |writer| {
                unsafe { writer.write_slice_t(&ints).unwrap() };
            }, prop_assert_eq!(&buffer, &bytes));
        }
    }
}