bytesbuf 0.5.6

Types for creating and manipulating byte sequences.
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! We separate out all the consumption methods for ease of maintenance.

use std::mem::MaybeUninit;
use std::ptr;

use num_traits::FromBytes;

use crate::BytesView;

impl BytesView {
    /// Consumes a `u8` from the byte sequence.
    ///
    /// The consumed byte is dropped from the view, moving any remaining bytes to the front.
    ///
    /// If permitted by memory layout considerations and reference counts, the memory capacity
    /// backing the dropped bytes is released back to the memory provider.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// let mut view = BytesView::copied_from_slice(b"ABC", &memory);
    ///
    /// assert_eq!(view.get_byte(), b'A');
    /// assert_eq!(view.get_byte(), b'B');
    /// assert_eq!(view.get_byte(), b'C');
    /// assert!(view.is_empty());
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the view does not cover enough bytes of data.
    #[inline]
    #[must_use]
    pub fn get_byte(&mut self) -> u8 {
        // The first span (last in reverse order) backs the next byte. Stored spans are never
        // empty (type invariant), so reading its first byte and advancing over it in one pass
        // avoids the general `advance` loop and a second span lookup.
        let front = self.spans_reversed.last_mut().expect("view must cover at least one byte");

        let byte = front[0];

        if front.len() == 1 {
            self.spans_reversed.pop();
        } else {
            // SAFETY: the span has at least two bytes, so advancing by one stays in bounds.
            unsafe {
                front.advance(1);
            }
        }

        // The view covered at least one byte, which we just removed from the front span.
        self.shrink_len(1);

        byte
    }

    /// Transfers bytes into an initialized slice.
    ///
    /// The copied bytes are dropped from the view, moving any remaining bytes to the front.
    ///
    /// If permitted by memory layout considerations and reference counts, the memory capacity
    /// backing the dropped bytes is released back to the memory provider.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// let mut view = BytesView::copied_from_slice(b"Hello, world!", &memory);
    ///
    /// let mut buffer = [0u8; 5];
    /// view.copy_to_slice(&mut buffer);
    ///
    /// assert_eq!(&buffer, b"Hello");
    /// assert_eq!(view.len(), 8); // ", world!" remains
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the destination is larger than the view.
    pub fn copy_to_slice(&mut self, mut dst: &mut [u8]) {
        assert!(self.len() >= dst.len());

        // The general slice-walking loop is intentional. A single-span fast path (copying directly
        // when the destination fits within the first slice) trims a few instructions but leaves
        // wall-clock time unchanged, because the per-call cost is dominated by the `advance` span
        // bookkeeping the loop already performs. Adding `unsafe` for a flat result is not worth it.
        while !dst.is_empty() {
            let src = self.first_slice();
            let bytes_to_copy = dst.len().min(src.len());

            dst[..bytes_to_copy].copy_from_slice(&src[..bytes_to_copy]);
            dst = &mut dst[bytes_to_copy..];

            self.advance(bytes_to_copy);
        }
    }

    /// Transfers bytes into a potentially uninitialized slice.
    ///
    /// The copied bytes are dropped from the view, moving any remaining bytes to the front.
    ///
    /// If permitted by memory layout considerations and reference counts, the memory capacity
    /// backing the dropped bytes is released back to the memory provider.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use std::mem::MaybeUninit;
    ///
    /// use bytesbuf::BytesView;
    ///
    /// let mut view = BytesView::copied_from_slice(b"Hello", &memory);
    ///
    /// let mut buffer: [MaybeUninit<u8>; 5] = [const { MaybeUninit::uninit() }; 5];
    /// view.copy_to_uninit_slice(&mut buffer);
    ///
    /// // SAFETY: The buffer has been fully initialized by copy_to_uninit_slice.
    /// let buffer: [u8; 5] = unsafe { std::mem::transmute(buffer) };
    /// assert_eq!(&buffer, b"Hello");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the destination is larger than the view.
    pub fn copy_to_uninit_slice(&mut self, mut dst: &mut [MaybeUninit<u8>]) {
        assert!(self.len() >= dst.len());

        while !dst.is_empty() {
            let src = self.first_slice();
            let bytes_to_copy = dst.len().min(src.len());

            // SAFETY: Both are byte slices, so no alignment concerns.
            // We guard against length overflow via min() to constrain to slice length.
            unsafe {
                ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr().cast(), bytes_to_copy);
            }

            dst = &mut dst[bytes_to_copy..];

            self.advance(bytes_to_copy);
        }
    }

    /// Reads a `T` directly from the first span when that span fully contains it, consuming the
    /// bytes in a single span lookup. Returns `None` when the value straddles a span boundary, in
    /// which case the caller must fall back to buffered assembly.
    ///
    /// The caller must have already verified that the view covers at least `size_of::<T::Bytes>()`
    /// bytes.
    #[inline]
    // This is a behavior-preserving fast path: returning `None` (or declining the value that exactly
    // fills the first span) routes the caller to `get_num_*_buffered`, which produces an identical
    // result. Mutations that disable the fast path or shift its span-boundary check are therefore
    // functionally equivalent and cannot be observed by behavioral tests.
    #[cfg_attr(test, mutants::skip)]
    fn get_num_in_first_span<T, F>(&mut self, convert: F) -> Option<T>
    where
        T: FromBytes,
        T::Bytes: Sized,
        F: FnOnce(&T::Bytes) -> T,
    {
        let size = size_of::<T::Bytes>();

        let front = self.spans_reversed.last_mut()?;
        let front_len = front.len() as usize;

        if size > front_len {
            return None;
        }

        // SAFETY: the first span holds at least `size_of::<T::Bytes>()` bytes, so reading a
        // `T::Bytes` from its start stays in bounds. We use an unaligned read because the span is
        // backed by a byte buffer with no alignment guarantee, while `T::Bytes` may demand a larger
        // alignment; the read materializes a properly aligned local that we then borrow.
        let bytes_array = unsafe { ptr::read_unaligned(front.as_ptr().cast::<T::Bytes>()) };
        let result = convert(&bytes_array);

        if front_len == size {
            self.spans_reversed.pop();
        } else {
            // SAFETY: `size < front_len`, so advancing the span by `size` stays in bounds.
            unsafe {
                front.advance(size);
            }
        }

        // The caller verified the view covers at least `size` bytes, which we just removed.
        self.shrink_len(size);

        Some(result)
    }

    /// Consumes a number of type `T` in little-endian representation.
    ///
    /// The bytes of the `T` are dropped from the view, moving any remaining bytes to the front.
    ///
    /// If permitted by memory layout considerations and reference counts, the memory capacity
    /// backing the dropped bytes is released back to the memory provider.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// // Little-endian: least significant byte first.
    /// let data: &[u8] = &[
    ///     0x34, 0x12, // u16: 0x1234
    ///     0x78, 0x56, 0x34, 0x12, // u32: 0x12345678
    /// ];
    /// let mut view = BytesView::copied_from_slice(data, &memory);
    ///
    /// assert_eq!(view.get_num_le::<u16>(), 0x1234);
    /// assert_eq!(view.get_num_le::<u32>(), 0x12345678);
    /// assert!(view.is_empty());
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the view does not cover enough bytes of data.
    #[inline]
    #[must_use]
    pub fn get_num_le<T: FromBytes>(&mut self) -> T
    where
        T::Bytes: Sized,
    {
        let size = size_of::<T::Bytes>();
        assert!(self.len() >= size);

        if let Some(result) = self.get_num_in_first_span::<T, _>(T::from_le_bytes) {
            return result;
        }

        // The value straddles a span boundary, so we collect bytes into an intermediate buffer
        // and deserialize from there.
        // SAFETY: We guarantee the view covers enough bytes - we checked it above.
        unsafe { self.get_num_le_buffered() }
    }

    /// # Safety
    ///
    /// The caller is responsible for ensuring that the view covers enough bytes.
    /// We do not duplicate length checking as this method is only assumed to be
    /// called as a fallback when non-buffered reading proved impossible.
    #[cold] // Most reads will not straddle a slice boundary and not require buffering.
    unsafe fn get_num_le_buffered<T: FromBytes>(&mut self) -> T
    where
        T::Bytes: Sized,
    {
        let mut buffer: MaybeUninit<T::Bytes> = MaybeUninit::uninit();
        let mut buffer_cursor = buffer.as_mut_ptr().cast::<u8>();

        let mut bytes_remaining = size_of::<T::Bytes>();

        while bytes_remaining > 0 {
            let first_slice = self.first_slice();
            let bytes_to_copy = bytes_remaining.min(first_slice.len());

            // SAFETY: The caller has guaranteed that the view covers enough bytes.
            // We only copy up to bytes_remaining, which is at most size_of::<T::Bytes>(),
            // so we will not overflow the buffer.
            // Both sides are byte arrays/slices so there are no alignment concerns.
            unsafe {
                ptr::copy_nonoverlapping(first_slice.as_ptr(), buffer_cursor, bytes_to_copy);
            }

            // This cannot overflow because we it is guarded by min() above.
            bytes_remaining = bytes_remaining.wrapping_sub(bytes_to_copy);

            // SAFETY: We are advancing the cursor in-bounds of the buffer.
            buffer_cursor = unsafe { buffer_cursor.add(bytes_to_copy) };

            self.advance(bytes_to_copy);
        }

        // SAFETY: We have filled the buffer with data, initializing it fully.
        T::from_le_bytes(&unsafe { buffer.assume_init() })
    }

    /// Consumes a number of type `T` in big-endian representation.
    ///
    /// The bytes of the `T` are dropped from the view, moving any remaining bytes to the front.
    ///
    /// If permitted by memory layout considerations and reference counts, the memory capacity
    /// backing the dropped bytes is released back to the memory provider.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// // Big-endian: most significant byte first.
    /// let data: &[u8] = &[
    ///     0x12, 0x34, 0x56, 0x78, // u32: 0x12345678
    ///     0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, // u64: 0x0123456789ABCDEF
    /// ];
    /// let mut view = BytesView::copied_from_slice(data, &memory);
    ///
    /// assert_eq!(view.get_num_be::<u32>(), 0x12345678);
    /// assert_eq!(view.get_num_be::<u64>(), 0x0123456789ABCDEF);
    /// assert!(view.is_empty());
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the view does not cover enough bytes of data.
    #[inline]
    #[must_use]
    pub fn get_num_be<T: FromBytes>(&mut self) -> T
    where
        T::Bytes: Sized,
    {
        let size = size_of::<T::Bytes>();
        assert!(self.len() >= size);

        if let Some(result) = self.get_num_in_first_span::<T, _>(T::from_be_bytes) {
            return result;
        }

        // The value straddles a span boundary, so we collect bytes into an intermediate buffer
        // and deserialize from there.
        // SAFETY: We guarantee the view covers enough bytes - we checked it above.
        unsafe { self.get_num_be_buffered() }
    }

    /// # Safety
    ///
    /// The caller is responsible for ensuring that the view covers enough bytes.
    /// We do not duplicate length checking as this method is only assumed to be
    /// called as a fallback when non-buffered reading proved impossible.
    #[cold] // Most reads will not straddle a slice boundary and not require buffering.
    unsafe fn get_num_be_buffered<T: FromBytes>(&mut self) -> T
    where
        T::Bytes: Sized,
    {
        let mut buffer: MaybeUninit<T::Bytes> = MaybeUninit::uninit();
        let mut buffer_cursor = buffer.as_mut_ptr().cast::<u8>();

        let mut bytes_remaining = size_of::<T::Bytes>();

        while bytes_remaining > 0 {
            let first_slice = self.first_slice();
            let bytes_to_copy = bytes_remaining.min(first_slice.len());

            // SAFETY: The caller has guaranteed that the view covers enough bytes.
            // We only copy up to bytes_remaining, which is at most size_of::<T::Bytes>(),
            // so we will not overflow the buffer.
            // Both sides are byte arrays/slices so there are no alignment concerns.
            unsafe {
                ptr::copy_nonoverlapping(first_slice.as_ptr(), buffer_cursor, bytes_to_copy);
            }

            // This cannot overflow because we it is guarded by min() above.
            bytes_remaining = bytes_remaining.wrapping_sub(bytes_to_copy);

            // SAFETY: We are advancing the cursor in-bounds of the buffer.
            buffer_cursor = unsafe { buffer_cursor.add(bytes_to_copy) };

            self.advance(bytes_to_copy);
        }

        // SAFETY: We have filled the buffer with data, initializing it fully.
        T::from_be_bytes(&unsafe { buffer.assume_init() })
    }

    /// Consumes a number of type `T` in native-endian representation.
    ///
    /// The bytes of the `T` are dropped from the view, moving any remaining bytes to the front.
    ///
    /// If permitted by memory layout considerations and reference counts, the memory capacity
    /// backing the dropped bytes is released back to the memory provider.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// // Native-endian: byte order matches the platform.
    /// let value1: u16 = 0x1234;
    /// let value2: u64 = 0x0123456789ABCDEF;
    ///
    /// let mut data = Vec::new();
    /// data.extend_from_slice(&value1.to_ne_bytes());
    /// data.extend_from_slice(&value2.to_ne_bytes());
    ///
    /// let mut view = BytesView::copied_from_slice(&data, &memory);
    ///
    /// assert_eq!(view.get_num_ne::<u16>(), 0x1234);
    /// assert_eq!(view.get_num_ne::<u64>(), 0x0123456789ABCDEF);
    /// assert!(view.is_empty());
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the view does not cover enough bytes of data.
    #[inline]
    #[must_use]
    pub fn get_num_ne<T: FromBytes>(&mut self) -> T
    where
        T::Bytes: Sized,
    {
        let size = size_of::<T::Bytes>();
        assert!(self.len() >= size);

        if let Some(result) = self.get_num_in_first_span::<T, _>(T::from_ne_bytes) {
            return result;
        }

        // The value straddles a span boundary, so we collect bytes into an intermediate buffer
        // and deserialize from there.
        // SAFETY: We guarantee the view covers enough bytes - we checked it above.
        unsafe { self.get_num_ne_buffered() }
    }

    /// # Safety
    ///
    /// The caller is responsible for ensuring that the view covers enough bytes.
    /// We do not duplicate length checking as this method is only assumed to be
    /// called as a fallback when non-buffered reading proved impossible.
    #[cold] // Most reads will not straddle a slice boundary and not require buffering.
    unsafe fn get_num_ne_buffered<T: FromBytes>(&mut self) -> T
    where
        T::Bytes: Sized,
    {
        let mut buffer: MaybeUninit<T::Bytes> = MaybeUninit::uninit();
        let mut buffer_cursor = buffer.as_mut_ptr().cast::<u8>();

        let mut bytes_remaining = size_of::<T::Bytes>();

        while bytes_remaining > 0 {
            let first_slice = self.first_slice();
            let bytes_to_copy = bytes_remaining.min(first_slice.len());

            // SAFETY: The caller has guaranteed that the view covers enough bytes.
            // We only copy up to bytes_remaining, which is at most size_of::<T::Bytes>(),
            // so we will not overflow the buffer.
            // Both sides are byte arrays/slices so there are no alignment concerns.
            unsafe {
                ptr::copy_nonoverlapping(first_slice.as_ptr(), buffer_cursor, bytes_to_copy);
            }

            // This cannot overflow because we it is guarded by min() above.
            bytes_remaining = bytes_remaining.wrapping_sub(bytes_to_copy);

            // SAFETY: We are advancing the cursor in-bounds of the buffer.
            buffer_cursor = unsafe { buffer_cursor.add(bytes_to_copy) };

            self.advance(bytes_to_copy);
        }

        // SAFETY: We have filled the buffer with data, initializing it fully.
        T::from_ne_bytes(&unsafe { buffer.assume_init() })
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::mem::testing::TransparentMemory;

    #[test]
    fn get_byte() {
        let memory = TransparentMemory::new();
        let mut view = BytesView::copied_from_slice(&[1, 2, 3, 4], &memory);

        assert_eq!(view.get_byte(), 1);
        assert_eq!(view.get_byte(), 2);
        assert_eq!(view.get_byte(), 3);
        assert_eq!(view.get_byte(), 4);
        assert!(view.is_empty());
    }

    #[test]
    fn copy_to_slice() {
        let memory = TransparentMemory::new();
        let mut view = BytesView::copied_from_slice(&[1, 2, 3, 4], &memory);

        let mut dst = [0u8; 4];
        view.copy_to_slice(&mut dst);

        assert_eq!(dst, [1, 2, 3, 4]);
        assert!(view.is_empty());
    }

    #[test]
    fn copy_to_smaller_slice_copies_partially() {
        let memory = TransparentMemory::new();
        let mut view = BytesView::copied_from_slice(&[1, 2, 3, 4], &memory);

        let mut dst = [0u8; 3];
        view.copy_to_slice(&mut dst);

        assert_eq!(dst, [1, 2, 3]);
        assert_eq!(view.len(), 1);
    }

    #[test]
    #[should_panic]
    fn copy_to_bigger_slice_panics() {
        let memory = TransparentMemory::new();
        let mut view = BytesView::copied_from_slice(&[1, 2, 3, 4], &memory);

        let mut dst = [0u8; 8];
        view.copy_to_slice(&mut dst);
    }

    #[test]
    fn copy_to_uninit_slice() {
        let memory = TransparentMemory::new();
        let mut view = BytesView::copied_from_slice(&[1, 2, 3, 4], &memory);

        let mut dst = [MaybeUninit::<u8>::uninit(); 4];
        view.copy_to_uninit_slice(&mut dst);

        // SAFETY: It has now been initialized.
        let dst = unsafe { std::mem::transmute::<[MaybeUninit<u8>; 4], [u8; 4]>(dst) };

        assert_eq!(dst, [1, 2, 3, 4]);
        assert!(view.is_empty());
    }

    #[test]
    fn copy_to_uninit_smaller_slice_copies_partially() {
        let memory = TransparentMemory::new();
        let mut view = BytesView::copied_from_slice(&[1, 2, 3, 4], &memory);

        let mut dst = [MaybeUninit::<u8>::uninit(); 3];
        view.copy_to_uninit_slice(&mut dst);

        // SAFETY: It has now been initialized.
        let dst = unsafe { std::mem::transmute::<[MaybeUninit<u8>; 3], [u8; 3]>(dst) };

        assert_eq!(dst, [1, 2, 3]);
        assert_eq!(view.len(), 1);
    }

    #[test]
    #[should_panic]
    fn copy_to_uninit_bigger_slice_panics() {
        let memory = TransparentMemory::new();
        let mut view = BytesView::copied_from_slice(&[1, 2, 3, 4], &memory);

        let mut dst = [MaybeUninit::<u8>::uninit(); 8];
        view.copy_to_uninit_slice(&mut dst);
    }

    #[test]
    fn copy_to_slice_multi_span() {
        let memory = TransparentMemory::new();
        let data_part1 = [10_u8, 20];
        let data_part2 = [30_u8, 40, 50];
        let view_part1 = BytesView::copied_from_slice(&data_part1, &memory);
        let view_part2 = BytesView::copied_from_slice(&data_part2, &memory);
        let mut view_combined = BytesView::from_views([view_part1, view_part2]);

        let mut dst = [0u8; 5];
        view_combined.copy_to_slice(&mut dst);
        assert!(view_combined.is_empty());

        assert_eq!(dst, [10_u8, 20, 30, 40, 50]);
    }

    #[test]
    fn copy_to_uninit_slice_multi_span() {
        let memory = TransparentMemory::new();
        let data_part1 = [10_u8, 20];
        let data_part2 = [30_u8, 40, 50];
        let view_part1 = BytesView::copied_from_slice(&data_part1, &memory);
        let view_part2 = BytesView::copied_from_slice(&data_part2, &memory);
        let mut view_combined = BytesView::from_views([view_part1, view_part2]);

        let mut dst = [MaybeUninit::<u8>::uninit(); 5];
        view_combined.copy_to_uninit_slice(&mut dst);
        assert!(view_combined.is_empty());

        // SAFETY: It has now been initialized.
        let dst = unsafe { std::mem::transmute::<[MaybeUninit<u8>; 5], [u8; 5]>(dst) };

        assert_eq!(dst, [10_u8, 20, 30, 40, 50]);
    }

    #[test]
    fn get_num_le() {
        let memory = TransparentMemory::new();
        let mut view = BytesView::copied_from_slice(&[0x34, 0x12, 0x78, 0x56], &memory);

        assert_eq!(view.get_num_le::<u16>(), 0x1234);
        assert_eq!(view.get_num_le::<u16>(), 0x5678);

        assert!(view.is_empty());
    }

    #[test]
    fn get_num_le_multi_span() {
        let memory = TransparentMemory::new();
        let data_part1 = [0x78_u8, 0x56];
        let data_part2 = [0x34_u8, 0x12];
        let view_part1 = BytesView::copied_from_slice(&data_part1, &memory);
        let view_part2 = BytesView::copied_from_slice(&data_part2, &memory);
        let mut view_combined = BytesView::from_views([view_part1, view_part2]);

        assert_eq!(view_combined.get_num_le::<u32>(), 0x1234_5678);

        assert!(view_combined.is_empty());
    }

    #[test]
    fn get_num_be() {
        let memory = TransparentMemory::new();
        let mut view = BytesView::copied_from_slice(&[0x12, 0x34, 0x56, 0x78], &memory);

        assert_eq!(view.get_num_be::<u16>(), 0x1234);
        assert_eq!(view.get_num_be::<u16>(), 0x5678);

        assert!(view.is_empty());
    }

    #[test]
    fn get_num_be_multi_span() {
        let memory = TransparentMemory::new();
        let data_part1 = [0x12_u8, 0x34];
        let data_part2 = [0x56_u8, 0x78];
        let view_part1 = BytesView::copied_from_slice(&data_part1, &memory);
        let view_part2 = BytesView::copied_from_slice(&data_part2, &memory);
        let mut view_combined = BytesView::from_views([view_part1, view_part2]);

        assert_eq!(view_combined.get_num_be::<u32>(), 0x1234_5678);

        assert!(view_combined.is_empty());
    }

    #[test]
    fn get_num_ne() {
        let memory = TransparentMemory::new();
        let mut view = BytesView::copied_from_slice(&[0x34, 0x12, 0x78, 0x56], &memory);

        if cfg!(target_endian = "big") {
            assert_eq!(view.get_num_ne::<u16>(), 0x3412);
            assert_eq!(view.get_num_ne::<u16>(), 0x7856);
        } else {
            assert_eq!(view.get_num_ne::<u16>(), 0x1234);
            assert_eq!(view.get_num_ne::<u16>(), 0x5678);
        }

        assert!(view.is_empty());
    }

    #[test]
    fn get_num_ne_multi_span() {
        let memory = TransparentMemory::new();
        let data_part1 = [0x78_u8, 0x56];
        let data_part2 = [0x34_u8, 0x12];
        let view_part1 = BytesView::copied_from_slice(&data_part1, &memory);
        let view_part2 = BytesView::copied_from_slice(&data_part2, &memory);
        let mut view_combined = BytesView::from_views([view_part1, view_part2]);

        if cfg!(target_endian = "big") {
            assert_eq!(view_combined.get_num_ne::<u32>(), 0x7856_3412);
        } else {
            assert_eq!(view_combined.get_num_ne::<u32>(), 0x1234_5678);
        }

        assert!(view_combined.is_empty());
    }

    /// Soundness coverage for `FromBytes` implementations whose `Bytes` associated type does not
    /// match the value type `T` in size or alignment.
    ///
    /// The standard integer and float types use `Bytes = [u8; size_of::<T>()]`, so for them
    /// `size_of::<T>() == size_of::<T::Bytes>()` and `align_of::<T::Bytes>() == 1`. The numeric
    /// reads must size, advance, and bound by `T::Bytes` (not `T`) and must tolerate any source
    /// alignment, which only these custom types can exercise.
    #[cfg_attr(coverage_nightly, coverage(off))]
    mod from_bytes_soundness {
        use std::borrow::{Borrow, BorrowMut};

        use num_traits::FromBytes;

        use crate::BytesView;
        use crate::mem::testing::TransparentMemory;

        /// `Bytes` is wider than the value it produces: `size_of::<NarrowValue>() == 1` while the
        /// serialized form is four bytes. Sizing reads by `size_of::<T>()` would read past a
        /// one-byte first-span slice and leave the buffered path's `MaybeUninit<[u8; 4]>` only
        /// partially initialized before `assume_init`.
        #[derive(Debug, PartialEq, Eq, Clone, Copy)]
        struct NarrowValue(u8);

        impl FromBytes for NarrowValue {
            type Bytes = [u8; 4];

            fn from_le_bytes(bytes: &[u8; 4]) -> Self {
                Self(bytes[0])
            }

            fn from_be_bytes(bytes: &[u8; 4]) -> Self {
                Self(bytes[3])
            }
        }

        /// `Bytes` is narrower than the value it produces: `size_of::<WideValue>() == 8` while the
        /// serialized form is two bytes. Sizing reads by `size_of::<T>()` would over-advance the
        /// view and, in the buffered path, copy eight bytes into a two-byte `MaybeUninit<[u8; 2]>`
        /// buffer.
        #[derive(Debug, PartialEq, Eq, Clone, Copy)]
        struct WideValue(u64);

        impl FromBytes for WideValue {
            type Bytes = [u8; 2];

            fn from_le_bytes(bytes: &[u8; 2]) -> Self {
                Self(u16::from_le_bytes(*bytes).into())
            }

            fn from_be_bytes(bytes: &[u8; 2]) -> Self {
                Self(u16::from_be_bytes(*bytes).into())
            }
        }

        /// A `Bytes` type whose alignment exceeds one. Constructing a `&OverAligned` reference from
        /// an unaligned byte-slice pointer is undefined behavior, so the read must materialize the
        /// value through an alignment-agnostic copy. `NumBytes` is satisfied via its blanket impl
        /// over the manual `AsRef`/`AsMut`/`Borrow`/`BorrowMut` and the derived comparison traits.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        #[repr(align(8))]
        struct OverAligned([u8; 8]);

        impl AsRef<[u8]> for OverAligned {
            fn as_ref(&self) -> &[u8] {
                &self.0
            }
        }

        impl AsMut<[u8]> for OverAligned {
            fn as_mut(&mut self) -> &mut [u8] {
                &mut self.0
            }
        }

        impl Borrow<[u8]> for OverAligned {
            fn borrow(&self) -> &[u8] {
                &self.0
            }
        }

        impl BorrowMut<[u8]> for OverAligned {
            fn borrow_mut(&mut self) -> &mut [u8] {
                &mut self.0
            }
        }

        #[derive(Debug, PartialEq, Eq, Clone, Copy)]
        struct OverAlignedValue(u64);

        impl FromBytes for OverAlignedValue {
            type Bytes = OverAligned;

            fn from_le_bytes(bytes: &OverAligned) -> Self {
                Self(u64::from_le_bytes(bytes.0))
            }

            fn from_be_bytes(bytes: &OverAligned) -> Self {
                Self(u64::from_be_bytes(bytes.0))
            }
        }

        #[test]
        fn narrow_bytes_le_single_span() {
            let memory = TransparentMemory::new();
            let mut view = BytesView::copied_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD], &memory);

            // Four bytes are consumed even though the value occupies a single byte.
            assert_eq!(view.get_num_le::<NarrowValue>(), NarrowValue(0xAA));
            assert!(view.is_empty());
        }

        #[test]
        fn narrow_bytes_be_single_span() {
            let memory = TransparentMemory::new();
            let mut view = BytesView::copied_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD], &memory);

            assert_eq!(view.get_num_be::<NarrowValue>(), NarrowValue(0xDD));
            assert!(view.is_empty());
        }

        #[test]
        fn narrow_bytes_le_multi_span() {
            let memory = TransparentMemory::new();
            let view_part1 = BytesView::copied_from_slice(&[0xAA, 0xBB], &memory);
            let view_part2 = BytesView::copied_from_slice(&[0xCC, 0xDD], &memory);
            let mut view = BytesView::from_views([view_part1, view_part2]);

            // The value straddles the span boundary, forcing the buffered path to fill all four
            // bytes of the `MaybeUninit<[u8; 4]>` before `assume_init`.
            assert_eq!(view.get_num_le::<NarrowValue>(), NarrowValue(0xAA));
            assert!(view.is_empty());
        }

        #[test]
        fn wide_bytes_le_single_span() {
            let memory = TransparentMemory::new();
            let mut view = BytesView::copied_from_slice(&[0x34, 0x12, 0x78, 0x56], &memory);

            // Each read advances by exactly two bytes (the size of `Bytes`), not eight.
            assert_eq!(view.get_num_le::<WideValue>(), WideValue(0x1234));
            assert_eq!(view.get_num_le::<WideValue>(), WideValue(0x5678));
            assert!(view.is_empty());
        }

        #[test]
        fn wide_bytes_be_single_span() {
            let memory = TransparentMemory::new();
            let mut view = BytesView::copied_from_slice(&[0x12, 0x34, 0x56, 0x78], &memory);

            assert_eq!(view.get_num_be::<WideValue>(), WideValue(0x1234));
            assert_eq!(view.get_num_be::<WideValue>(), WideValue(0x5678));
            assert!(view.is_empty());
        }

        #[test]
        fn wide_bytes_le_multi_span() {
            let memory = TransparentMemory::new();
            let view_part1 = BytesView::copied_from_slice(&[0x34], &memory);
            let view_part2 = BytesView::copied_from_slice(&[0x12], &memory);
            let mut view = BytesView::from_views([view_part1, view_part2]);

            // The buffered path must size its copy by `Bytes` (two bytes), not by the eight-byte
            // value type, to avoid overflowing the `MaybeUninit<[u8; 2]>` buffer.
            assert_eq!(view.get_num_le::<WideValue>(), WideValue(0x1234));
            assert!(view.is_empty());
        }

        const OVER_ALIGNED_VALUE: u64 = 0x0123_4567_89AB_CDEF;

        #[test]
        fn over_aligned_le_single_span() {
            let memory = TransparentMemory::new();
            let mut view = BytesView::copied_from_slice(&OVER_ALIGNED_VALUE.to_le_bytes(), &memory);

            assert_eq!(view.get_num_le::<OverAlignedValue>(), OverAlignedValue(OVER_ALIGNED_VALUE));
            assert!(view.is_empty());
        }

        #[test]
        fn over_aligned_le_misaligned_single_span() {
            let memory = TransparentMemory::new();

            // A single leading byte that we drop, leaving the eight value bytes at an odd offset
            // from the allocation base. Whenever that base is itself eight-byte aligned (the
            // common case for the global allocator), the value bytes are misaligned for an
            // eight-byte read, so the fast path must not assume the source is aligned.
            let mut data = vec![0xFF_u8];
            data.extend_from_slice(&OVER_ALIGNED_VALUE.to_le_bytes());
            let mut view = BytesView::copied_from_slice(&data, &memory);

            assert_eq!(view.get_byte(), 0xFF);
            assert_eq!(view.get_num_le::<OverAlignedValue>(), OverAlignedValue(OVER_ALIGNED_VALUE));
            assert!(view.is_empty());
        }

        #[test]
        fn over_aligned_le_multi_span() {
            let memory = TransparentMemory::new();
            let bytes = OVER_ALIGNED_VALUE.to_le_bytes();
            let view_part1 = BytesView::copied_from_slice(&bytes[..3], &memory);
            let view_part2 = BytesView::copied_from_slice(&bytes[3..], &memory);
            let mut view = BytesView::from_views([view_part1, view_part2]);

            // The buffered path assembles the value in a properly aligned `MaybeUninit<OverAligned>`.
            assert_eq!(view.get_num_le::<OverAlignedValue>(), OverAlignedValue(OVER_ALIGNED_VALUE));
            assert!(view.is_empty());
        }

        #[test]
        fn over_aligned_ne_misaligned_single_span() {
            let memory = TransparentMemory::new();

            let mut data = vec![0xFF_u8];
            data.extend_from_slice(&OVER_ALIGNED_VALUE.to_ne_bytes());
            let mut view = BytesView::copied_from_slice(&data, &memory);

            assert_eq!(view.get_byte(), 0xFF);
            assert_eq!(view.get_num_ne::<OverAlignedValue>(), OverAlignedValue(OVER_ALIGNED_VALUE));
            assert!(view.is_empty());
        }
    }
}