bytesbuf 0.4.2

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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::iter;
use std::num::NonZero;
use std::ops::{Bound, RangeBounds};

use nm::{Event, Magnitude};
use smallvec::SmallVec;

use crate::mem::{BlockMeta, BlockSize, Memory};
use crate::{MAX_INLINE_SPANS, MemoryGuard, Span};

/// A view over a sequence of immutable bytes.
///
/// Only the contents are immutable - the view itself can be mutated in terms of progressively
/// marking the byte sequence as consumed until the view becomes empty.
///
/// # Creating a `BytesView`
///
/// Instances can be created in different ways:
///
/// * Use a [`BytesBuf`] to build the byte sequence piece by piece, consuming the buffered data as a new `BytesView` when finished.
/// * Clone an existing `BytesView` with [`clone()`].
/// * Take a range of bytes from an existing `BytesView` via [`range()`].
/// * Combine multiple `BytesView` instances into one via [`from_views()`], [`concat()`] or [`append()`].
/// * Copy data from a `&[u8]` using [`copied_from_slice()`].
///
/// Some of these methods may require you to first [obtain access to a memory provider].
#[doc = include_str!("../doc/snippets/sequence_memory_layout.md")]
///
/// # Example
///
/// ```
/// # let memory = bytesbuf::mem::GlobalPool::new();
/// use bytesbuf::BytesView;
///
/// let mut view = BytesView::copied_from_slice(b"Hello!", &memory);
///
/// // Read bytes one at a time until the view is empty.
/// while !view.is_empty() {
///     let byte = view.get_byte();
///     println!("Read byte: {byte}");
/// }
///
/// assert!(view.is_empty());
/// ```
///
/// [`BytesBuf`]: crate::BytesBuf
/// [`copied_from_slice()`]: Self::copied_from_slice
/// [`concat()`]: Self::concat
/// [`append()`]: Self::append
/// [`range()`]: Self::range
/// [`from_views()`]: Self::from_views
/// [`clone()`]: Self::clone
/// [obtain access to a memory provider]: crate#producing-byte-sequences
#[derive(Clone, Debug)]
pub struct BytesView {
    /// The spans of the byte sequence, stored in reverse order for efficient consumption
    /// by popping items off the end of the collection.
    pub(crate) spans_reversed: SmallVec<[Span; MAX_INLINE_SPANS]>,

    /// We cache the length so we do not have to recalculate it every time it is queried.
    len: usize,
}

impl BytesView {
    /// Creates a view over a zero-sized byte sequence.
    ///
    /// Use a [`BytesBuf`] to create a view over some actual data.
    ///
    /// [`BytesBuf`]: crate::BytesBuf
    #[cfg_attr(test, mutants::skip)] // Generates no-op mutations, not useful.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            spans_reversed: SmallVec::new_const(),
            len: 0,
        }
    }

    pub(crate) fn from_spans_reversed(spans_reversed: SmallVec<[Span; MAX_INLINE_SPANS]>) -> Self {
        #[cfg(debug_assertions)]
        spans_reversed.iter().for_each(|span| assert!(!span.is_empty()));

        // We can use this to fine-tune the inline span count once we have real-world data.
        VIEW_CREATED_SPANS.with(|x| x.observe(spans_reversed.len()));

        let len = spans_reversed.iter().fold(0_usize, |acc, span: &Span| {
            acc.checked_add(span.len() as usize)
                .expect("attempted to create a BytesView larger than usize::MAX bytes")
        });

        Self { spans_reversed, len }
    }

    /// (For testing) Concatenates a number of spans, yielding a view that combines the spans.
    ///
    /// Later changes made to the input spans will not be reflected in the resulting view.
    #[cfg(test)]
    pub(crate) fn from_spans<I>(spans: I) -> Self
    where
        I: IntoIterator<Item = Span>,
        <I as IntoIterator>::IntoIter: iter::DoubleEndedIterator,
    {
        let spans_reversed = spans.into_iter().rev().collect::<SmallVec<_>>();

        Self::from_spans_reversed(spans_reversed)
    }

    /// Concatenates a number of existing byte sequences, yielding a combined view.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// let header = BytesView::copied_from_slice(b"HTTP/1.1 ", &memory);
    /// let status = BytesView::copied_from_slice(b"200 ", &memory);
    /// let message = BytesView::copied_from_slice(b"OK", &memory);
    ///
    /// let response_line = BytesView::from_views([header, status, message]);
    ///
    /// assert_eq!(response_line.len(), 15);
    /// assert_eq!(response_line, b"HTTP/1.1 200 OK");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the resulting view would be larger than `usize::MAX` bytes.
    pub fn from_views<I>(views: I) -> Self
    where
        I: IntoIterator<Item = Self>,
        <I as IntoIterator>::IntoIter: iter::DoubleEndedIterator,
    {
        // Note that this requires the SmallVec to resize on the fly because thanks to the
        // two-level mapping here, there is no usable size hint that lets it know the size in
        // advance. If we had the span count here, we could avoid some allocations.

        // For a given input ABC123.
        let spans_reversed: SmallVec<_> = views
            .into_iter()
            // We first reverse the views: 123ABC.
            .rev()
            // And from inside each view we take the reversed spans: 321CBA.
            .flat_map(|view| view.spans_reversed)
            // Which become our final SmallVec of spans. Great success!
            .collect();

        Self::from_spans_reversed(spans_reversed)
    }

    /// Creates a `BytesView` by copying the contents of a `&[u8]`.
    ///
    /// # Example
    ///
    /// ```
    /// # struct TcpConnection;
    /// # impl TcpConnection {
    /// #     fn memory(&self) -> impl bytesbuf::mem::Memory { bytesbuf::mem::GlobalPool::new() }
    /// # }
    /// # let tcp_connection = TcpConnection;
    /// use bytesbuf::BytesView;
    ///
    /// const CONTENT_TYPE_KEY: &[u8] = b"Content-Type: ";
    ///
    /// let header_key = BytesView::copied_from_slice(CONTENT_TYPE_KEY, &tcp_connection.memory());
    ///
    /// assert_eq!(header_key.len(), 14);
    /// ```
    ///
    /// # Reusing without copying
    ///
    /// There is intentionally no mechanism in the `bytesbuf` crate to reference an existing
    /// `&[u8]` without copying the contents, even if it has a `'static` lifetime.
    ///
    /// The purpose of this limitation is to discourage accidentally involving arbitrary
    /// memory in high-performance I/O workflows. For efficient I/O processing, data must
    /// be stored in memory configured according to the needs of the consuming I/O endpoint,
    /// which is not the case for an arbitrary `&'static [u8]`.
    ///
    /// To reuse memory allocations, you need to reuse `BytesView` instances themselves.
    /// See the `bb_reuse.rs` example in the `bytesbuf` crate for a detailed example.
    #[must_use]
    pub fn copied_from_slice(bytes: &[u8], memory: &impl Memory) -> Self {
        let mut buf = memory.reserve(bytes.len());
        buf.put_slice(bytes);
        buf.consume_all()
    }

    pub(crate) fn into_spans_reversed(self) -> SmallVec<[Span; MAX_INLINE_SPANS]> {
        self.spans_reversed
    }

    /// The number of bytes exposed through the view.
    ///
    /// Consuming bytes from the view reduces its length.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// let mut view = BytesView::copied_from_slice(b"Hello", &memory);
    /// assert_eq!(view.len(), 5);
    ///
    /// _ = view.get_byte();
    /// assert_eq!(view.len(), 4);
    ///
    /// _ = view.get_num_le::<u16>();
    /// assert_eq!(view.len(), 2);
    /// ```
    #[cfg_attr(test, mutants::skip)] // Mutating this can cause infinite loops.
    #[must_use]
    pub fn len(&self) -> usize {
        // Sanity check.
        debug_assert_eq!(self.len, self.spans_reversed.iter().map(|x| x.len() as usize).sum::<usize>());

        self.len
    }

    /// Whether the view is of a zero-sized byte sequence.
    #[cfg_attr(test, mutants::skip)] // Mutating this can cause infinite loops.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Extends the lifetime of the memory capacity backing this view.
    ///
    /// This can be useful when unsafe code is used to reference the contents of a `BytesView` and it
    /// is possible to reach a condition where the `BytesView` itself no longer exists, even though
    /// the contents are referenced (e.g. because the remaining references are in non-Rust code).
    pub fn extend_lifetime(&self) -> MemoryGuard {
        MemoryGuard::new(self.spans_reversed.iter().map(Span::block_ref).map(Clone::clone))
    }

    /// Returns a range of the byte sequence.
    ///
    /// The bounds logic only considers data currently present in the view.
    /// Any data already consumed is not considered part of the view.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// let view = BytesView::copied_from_slice(b"Hello, world!", &memory);
    ///
    /// assert_eq!(view.range(0..5), b"Hello");
    /// assert_eq!(view.range(7..), b"world!");
    /// assert_eq!(view.range(..5), b"Hello");
    /// assert_eq!(view.range(..), b"Hello, world!");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the provided range is outside the bounds of the view.
    #[must_use]
    pub fn range<R>(&self, range: R) -> Self
    where
        R: RangeBounds<usize>,
    {
        self.range_checked(range).expect("provided range out of view bounds")
    }

    /// Returns a range of the byte sequence or `None` if out of bounds.
    ///
    /// The bounds logic only considers data currently present in the view.
    /// Any data already consumed is not considered part of the view.
    #[must_use]
    #[expect(clippy::missing_panics_doc, reason = "only unreachable panics")]
    #[expect(clippy::too_many_lines, reason = "acceptable for now")]
    #[cfg_attr(test, mutants::skip)] // Mutations include impossible conditions that we cannot test as well as mutations that are functionally equivalent.
    pub fn range_checked<R>(&self, range: R) -> Option<Self>
    where
        R: RangeBounds<usize>,
    {
        let bytes_until_range = match range.start_bound() {
            Bound::Included(&x) => x,
            Bound::Excluded(&x) => x.checked_add(1)?,
            Bound::Unbounded => 0,
        };

        let bytes_in_range = match range.end_bound() {
            Bound::Included(&x) => x.checked_add(1)?.checked_sub(bytes_until_range)?,
            Bound::Excluded(&x) => x.checked_sub(bytes_until_range)?,
            Bound::Unbounded => self.len().checked_sub(bytes_until_range)?,
        };

        let required_len = bytes_until_range
            .checked_add(bytes_in_range)
            .expect("overflowing usize is impossible because we are calculating offset into usize-bounded range");

        if required_len > self.len() {
            // Did not have enough data to cover the range.
            return None;
        }

        if bytes_in_range == 0 {
            // Empty sequence is empty.
            return Some(Self::new());
        }

        // Take the spans from the end of our spans_reversed (the logical beginning), while taking
        // bytes in each span from the beginning of the span. We implement this in two passes:
        // 1. Identify relevant range of spans. The idea is that our slice may just be a tiny
        //    subset of the entire sequence and we should not be processing parts of the sequence
        //    that do not matter (either because they are before the slice or after it).
        // 2. Within the relevant spans, skip to the relevant bytes, take them, and ignore the rest.
        //    This may range across any number of spans, though due to the pre-filtering in step 1
        //    we know that we only need to skip the head/tail in the first and last span.

        // Our accounting is all "logical", content-based.
        // These are the outputs from the first pass.
        let mut spans_until_range: usize = 0;
        let mut spans_in_range: usize = 0;
        let mut bytes_to_skip_in_first_relevant_span: BlockSize = 0;
        let mut bytes_to_leave_in_last_relevant_span: BlockSize = 0;

        {
            let mut pass1_bytes_until_range = bytes_until_range;
            let mut pass1_bytes_in_range = bytes_in_range;

            for span in self.spans_reversed.iter().rev() {
                let bytes_in_span = span.len();
                let bytes_in_span_usize = bytes_in_span as usize;

                if pass1_bytes_until_range > 0 && bytes_in_span_usize <= pass1_bytes_until_range {
                    // This entire span is uninteresting for us - skip.
                    spans_until_range = spans_until_range
                        .checked_add(1)
                        .expect("overflowing usize is impossible because we are calculating chunks within usize-bounded range");
                    pass1_bytes_until_range = pass1_bytes_until_range
                        .checked_sub(bytes_in_span_usize)
                        .expect("somehow ended up with negative bytes remaining until range start - only possible if the math is wrong");
                    continue;
                }

                // If we got to this point, it is an interesting span.

                // If this is the last span, we need to account for the bytes we are leaving behind.
                bytes_to_leave_in_last_relevant_span = bytes_in_span;

                // If we are at this point, pass1_bytes_until_range is either zero or points to some
                // position within this span, so it is now `BlockSize` bounded.
                let pass1_bytes_until_range_block_size = pass1_bytes_until_range.try_into().expect("we are supposedly indicating a position inside a span but the offset is larger than a memory block range - algorithm error");

                // We may still have some prefix to remove, so not every byte is relevant.
                if pass1_bytes_until_range != 0 {
                    bytes_to_skip_in_first_relevant_span = pass1_bytes_until_range_block_size;

                    // The first span might also be the last span.
                    bytes_to_leave_in_last_relevant_span = bytes_to_leave_in_last_relevant_span
                        .checked_sub(bytes_to_skip_in_first_relevant_span)
                        .expect("somehow ended up with negative bytes remaining in span - only possible if the math is wrong");
                }

                #[expect(
                    clippy::cast_possible_truncation,
                    reason = "the usize never contains a value outside bounds of BlockSize - guarded by min()"
                )]
                let relevant_bytes_in_span = ((bytes_in_span
                    .checked_sub(pass1_bytes_until_range_block_size)
                    .expect("somehow ended up with negative bytes remaining in span - only possible if the math is wrong")
                    as usize)
                    .min(pass1_bytes_in_range)) as BlockSize;

                bytes_to_leave_in_last_relevant_span = bytes_to_leave_in_last_relevant_span
                    .checked_sub(relevant_bytes_in_span)
                    .expect("somehow ended up with negative bytes remaining in span - only possible if the math is wrong");

                // Whatever happened, we have reached the relevant range now.
                spans_in_range = spans_in_range
                    .checked_add(1)
                    .expect("overflowing usize is impossible because we are calculating chunks within usize-bounded range");

                pass1_bytes_until_range = 0;

                pass1_bytes_in_range = pass1_bytes_in_range
                    .checked_sub(relevant_bytes_in_span as usize)
                    .expect("somehow ended up with negative bytes remaining in range - only possible if the math is wrong");

                if pass1_bytes_in_range == 0 {
                    // We have reached the end of the range - remaining spans are not interesting.
                    break;
                }
            }
        }

        let relevant_spans = self.spans_reversed.iter().rev().skip(spans_until_range).take(spans_in_range);

        let mut bytes_remaining_in_range = bytes_in_range;

        // We skip bytes_to_skip_in_first_relevant_span.
        // Then we take until bytes_remaining_in_range runs out.
        // The end. We know that every span is relevant now.

        // NB! We have to for-iterate over the relevant spans and not blindly use .map() because
        // .map() is lazy and may be evaluated in a completely different order from what we would
        // expect "logically". The easiest way for us to control iteration order is to for-loop.
        let mut slice_spans = SmallVec::with_capacity(spans_in_range);

        // These are in REVERSE ORDER, same as we use in storage. So we start with the last span.
        for span in relevant_spans.rev() {
            let mut bytes_to_even_consider = span.len();

            // If this is nonzero, we must be looking at the last relevant span.
            if bytes_to_leave_in_last_relevant_span > 0 {
                bytes_to_even_consider = bytes_to_even_consider
                    .checked_sub(bytes_to_leave_in_last_relevant_span)
                    .expect("somehow ended up with negative bytes remaining in span - only possible if the math is wrong");

                bytes_to_leave_in_last_relevant_span = 0;
            }

            #[expect(
                clippy::cast_possible_truncation,
                reason = "the usize never contains a value outside bounds of BlockSize - guarded by min()"
            )]
            let mut max_take_bytes = (bytes_to_even_consider as usize).min(bytes_remaining_in_range) as BlockSize;

            // Now if this is the first logical span (last in our iteration), we need to skip
            // some from the start. The key challenge here is - how do we know it is the first?
            // Simply put - it is the first if it can supply all the remaining bytes.
            let is_first_span = bytes_remaining_in_range <= max_take_bytes as usize;

            if is_first_span && bytes_to_skip_in_first_relevant_span > 0 {
                let remainder_in_span = bytes_to_even_consider
                    .checked_sub(bytes_to_skip_in_first_relevant_span)
                    .expect("somehow ended up with negative bytes remaining in span - only possible if the math is wrong");

                max_take_bytes = max_take_bytes.min(remainder_in_span);

                bytes_remaining_in_range = bytes_remaining_in_range
                    .checked_sub(max_take_bytes as usize)
                    .expect("somehow ended up with negative bytes remaining - only possible if the math is wrong");

                let start = bytes_to_skip_in_first_relevant_span;
                let end = bytes_to_skip_in_first_relevant_span
                    .checked_add(max_take_bytes)
                    .expect("overflowing usize is impossible because we are calculating slice within usize-bounded range");

                bytes_to_skip_in_first_relevant_span = 0;

                slice_spans.push(span.slice(start..end));
            } else {
                bytes_remaining_in_range = bytes_remaining_in_range
                    .checked_sub(max_take_bytes as usize)
                    .expect("somehow ended up with negative bytes remaining - only possible if the math is wrong");

                slice_spans.push(span.slice(0..max_take_bytes));
            }
        }

        Some(Self {
            spans_reversed: slice_spans,
            len: bytes_in_range,
        })
    }

    /// Executes a function `f` on each slice, consuming them all.
    ///
    /// The slices that make up the view are iterated in order,
    /// providing each to `f`. The view becomes empty after this.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// // Create a multi-slice view by concatenating independent views.
    /// # let part1 = BytesView::copied_from_slice(b"Hello", &memory);
    /// # let part2 = BytesView::copied_from_slice(b", ", &memory);
    /// # let part3 = BytesView::copied_from_slice(b"world!", &memory);
    /// let mut view = BytesView::from_views([part1, part2, part3]);
    ///
    /// view.consume_all_slices(|slice| {
    ///     println!("Slice of {} bytes: {:?}", slice.len(), slice);
    /// });
    ///
    /// assert!(view.is_empty());
    /// ```
    pub fn consume_all_slices<F>(&mut self, mut f: F)
    where
        F: FnMut(&[u8]),
    {
        // TODO: This fn could just be .into_iter() - we have no real
        // need for the "consume pattern" here. Iterators are more idiomatic.
        while !self.is_empty() {
            let slice = self.first_slice();
            f(slice);
            self.advance(slice.len());
        }
    }

    /// References the first slice of bytes in the byte sequence.
    ///
    /// Returns an empty slice if the view is over a zero-sized byte sequence.
    #[doc = include_str!("../doc/snippets/sequence_memory_layout.md")]
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// let mut view = BytesView::copied_from_slice(b"0123456789ABCDEF", &memory);
    ///
    /// // Read the first 10 bytes without assuming the length of first_slice().
    /// let mut ten_bytes = Vec::with_capacity(10);
    ///
    /// while ten_bytes.len() < 10 {
    ///     let slice = view.first_slice();
    ///
    ///     let bytes_to_take = slice.len().min(10 - ten_bytes.len());
    ///
    ///     ten_bytes.extend_from_slice(&slice[..bytes_to_take]);
    ///     view.advance(bytes_to_take);
    /// }
    ///
    /// assert_eq!(ten_bytes, b"0123456789");
    /// ```
    #[cfg_attr(test, mutants::skip)] // Mutating this can cause infinite loops.
    #[must_use]
    pub fn first_slice(&self) -> &[u8] {
        self.spans_reversed.last().map_or::<&[u8], _>(&[], |span| span)
    }

    /// Iterates over all the slices that make up this view, together with their metadata.
    ///
    /// Each item is a tuple of `(data, meta)` where `data` is a byte slice and `meta` is the
    /// optional metadata of the memory block backing that slice.
    #[doc = include_str!("../doc/snippets/sequence_memory_layout.md")]
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// # struct PageAlignedMemory;
    /// use bytesbuf::BytesView;
    ///
    /// # let part1 = BytesView::copied_from_slice(b"Hello", &memory);
    /// # let part2 = BytesView::copied_from_slice(b"World", &memory);
    /// let view = BytesView::from_views([part1, part2]);
    ///
    /// for (data, meta) in view.slices() {
    ///     let is_page_aligned = meta.is_some_and(|m| m.is::<PageAlignedMemory>());
    ///     println!(
    ///         "Slice of {} bytes (page-aligned: {is_page_aligned})",
    ///         data.len()
    ///     );
    /// }
    /// ```
    ///
    /// See the stand-alone example `bb_optimal_path.rs` in the `bytesbuf` crate for
    /// a more detailed example of how to make use of the slice metadata.
    pub fn slices(&self) -> BytesViewSlices<'_> {
        BytesViewSlices::new(self)
    }

    /// Inspects the metadata of the [`first_slice()`].
    ///
    /// `None` if there is no metadata associated with the first slice or
    /// if the view is over a zero-sized byte sequence.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// # struct PageAlignedMemory;
    /// use bytesbuf::BytesView;
    ///
    /// let view = BytesView::copied_from_slice(b"Hello", &memory);
    ///
    /// let is_page_aligned = view
    ///     .first_slice_meta()
    ///     .is_some_and(|meta| meta.is::<PageAlignedMemory>());
    ///
    /// println!("First slice is page-aligned: {is_page_aligned}");
    /// ```
    ///
    /// See the stand-alone example `bb_optimal_path.rs` in the `bytesbuf` crate for
    /// a more detailed example of how to make use of the slice metadata.
    ///
    /// [`first_slice()`]: Self::first_slice
    #[must_use]
    pub fn first_slice_meta(&self) -> Option<&dyn BlockMeta> {
        self.spans_reversed.last().and_then(|span| span.block_ref().meta())
    }

    /// Removes the first `count` bytes from the front of the view.
    ///
    /// The consumed 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"0123456789ABCDEF", &memory);
    ///
    /// // Read the first 10 bytes without assuming the length of first_slice().
    /// let mut ten_bytes = Vec::with_capacity(10);
    ///
    /// while ten_bytes.len() < 10 {
    ///     let slice = view.first_slice();
    ///
    ///     let bytes_to_take = slice.len().min(10 - ten_bytes.len());
    ///
    ///     ten_bytes.extend_from_slice(&slice[..bytes_to_take]);
    ///     view.advance(bytes_to_take);
    /// }
    ///
    /// assert_eq!(ten_bytes, b"0123456789");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `count` is greater than the number of bytes remaining.
    #[cfg_attr(test, mutants::skip)] // Mutating this can cause infinite loops.
    pub fn advance(&mut self, mut count: usize) {
        self.len = self.len.checked_sub(count).expect("attempted to advance past end of the view");

        while count > 0 {
            let front = self
                .spans_reversed
                .last_mut()
                .expect("logic error - ran out of spans before advancing over their contents");
            let span_len = front.len() as usize;

            if count < span_len {
                // SAFETY: We must guarantee we advance in-bounds. The if statement guarantees that.
                unsafe {
                    front.advance(count);
                }
                break;
            }

            self.spans_reversed.pop();
            // Will never overflow because we already handled the count < span_len case.
            count = count.wrapping_sub(span_len);
        }
    }

    /// Appends another view to the end of this one.
    ///
    /// This is a zero-copy operation, reusing the memory capacity of the other view.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// let mut greeting = BytesView::copied_from_slice(b"Hello, ", &memory);
    /// let name = BytesView::copied_from_slice(b"world!", &memory);
    ///
    /// greeting.append(name);
    ///
    /// assert_eq!(greeting, b"Hello, world!");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the resulting view would be larger than `usize::MAX` bytes.
    pub fn append(&mut self, other: Self) {
        self.len = self
            .len
            .checked_add(other.len)
            .expect("attempted to create a BytesView larger than usize::MAX bytes");

        self.spans_reversed.insert_many(0, other.spans_reversed);
    }

    /// Returns a new view that concatenates this view with another.
    ///
    /// This is a zero-copy operation, reusing the memory capacity of the other view.
    ///
    /// # Example
    ///
    /// ```
    /// # let memory = bytesbuf::mem::GlobalPool::new();
    /// use bytesbuf::BytesView;
    ///
    /// let greeting = BytesView::copied_from_slice(b"Hello, ", &memory);
    /// let name = BytesView::copied_from_slice(b"world!", &memory);
    ///
    /// let message = greeting.concat(name);
    ///
    /// // Original view is unchanged.
    /// assert_eq!(greeting, b"Hello, ");
    /// // New view contains the concatenation.
    /// assert_eq!(message, b"Hello, world!");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the resulting view would be larger than `usize::MAX` bytes.
    #[must_use]
    pub fn concat(&self, other: Self) -> Self {
        let mut new_view = self.clone();
        new_view.append(other);
        new_view
    }
}

impl Default for BytesView {
    fn default() -> Self {
        Self::new()
    }
}

impl PartialEq for BytesView {
    fn eq(&self, other: &Self) -> bool {
        // We do not care about the structure, only the contents.
        if self.len() != other.len() {
            return false;
        }

        // The two views may have differently sized spans, so we only compare in steps
        // of the smallest span size offered by either view.

        // We iterate over spans_reversed using indices to avoid cloning the views,
        // which would increment atomic reference counts for every span.
        let mut self_span_idx = self.spans_reversed.len();
        let mut self_offset: usize = 0;
        let mut other_span_idx = other.spans_reversed.len();
        let mut other_offset: usize = 0;
        let mut remaining_bytes = self.len();

        while remaining_bytes > 0 {
            let self_span: &[u8] = &self.spans_reversed[self_span_idx - 1];
            let other_span: &[u8] = &other.spans_reversed[other_span_idx - 1];

            let self_slice = self_span
                .get(self_offset..)
                .expect("offset only advances within span length, reset to 0 on span boundary");
            let other_slice = other_span
                .get(other_offset..)
                .expect("offset only advances within span length, reset to 0 on span boundary");

            let comparison_len = NonZero::new(self_slice.len().min(other_slice.len()))
                .expect("both views said there are remaining bytes but we got an empty slice from at least one of them");

            let self_slice = self_slice.get(..comparison_len.get()).expect("guarded by min() above");
            let other_slice = other_slice.get(..comparison_len.get()).expect("guarded by min() above");

            if self_slice != other_slice {
                // Something is different. That is enough for a determination.
                return false;
            }

            // Advance within or past the current spans.
            self_offset += comparison_len.get();
            debug_assert!(self_offset <= self_span.len(), "guarded by min() above to never exceed span length");
            if self_offset == self_span.len() {
                self_span_idx -= 1;
                self_offset = 0;
            }

            other_offset += comparison_len.get();
            debug_assert!(
                other_offset <= other_span.len(),
                "guarded by min() above to never exceed span length"
            );
            if other_offset == other_span.len() {
                other_span_idx -= 1;
                other_offset = 0;
            }

            remaining_bytes = remaining_bytes
                .checked_sub(comparison_len.get())
                .expect("impossible to consume more bytes from the sequences than are remaining");
        }

        debug_assert_eq!(remaining_bytes, 0);

        true
    }
}

impl PartialEq<&[u8]> for BytesView {
    fn eq(&self, other: &&[u8]) -> bool {
        let mut other = *other;

        // We do not care about the structure, only the contents.

        if self.len() != other.len() {
            return false;
        }

        // We iterate over spans_reversed using an index to avoid cloning the view,
        // which would increment atomic reference counts for every span.
        let mut span_idx = self.spans_reversed.len();
        let mut span_offset: usize = 0;
        let mut remaining_bytes = self.len();

        while remaining_bytes > 0 {
            let span: &[u8] = &self.spans_reversed[span_idx - 1];
            let self_slice = span
                .get(span_offset..)
                .expect("offset only advances within span length, reset to 0 on span boundary");

            let slice_size = NonZero::new(self_slice.len())
                .expect("both sides of the comparison said there are remaining bytes but we got an empty slice from at least one of them");

            let self_slice = self_slice.get(..slice_size.get()).expect("already checked that remaining > 0");
            let other_slice = other.get(..slice_size.get()).expect("already checked that remaining > 0");

            if self_slice != other_slice {
                return false;
            }

            // Advance within or past the current span.
            span_offset += slice_size.get();
            debug_assert!(
                span_offset <= span.len(),
                "guarded by (..slice_size) logic above to never exceed span length"
            );
            if span_offset == span.len() {
                span_idx -= 1;
                span_offset = 0;
            }

            other = other.get(slice_size.get()..).expect("guarded by length check above");

            remaining_bytes = remaining_bytes
                .checked_sub(slice_size.get())
                .expect("impossible to consume more bytes from the sequences than are remaining");
        }

        debug_assert_eq!(remaining_bytes, 0);

        true
    }
}

impl PartialEq<BytesView> for &[u8] {
    fn eq(&self, other: &BytesView) -> bool {
        other.eq(self)
    }
}

impl<const LEN: usize> PartialEq<&[u8; LEN]> for BytesView {
    fn eq(&self, other: &&[u8; LEN]) -> bool {
        self.eq(&other.as_slice())
    }
}

impl<const LEN: usize> PartialEq<BytesView> for &[u8; LEN] {
    fn eq(&self, other: &BytesView) -> bool {
        other.eq(&self.as_slice())
    }
}

impl Eq for BytesView {}

/// Iterator over the slices of a [`BytesView`] and their metadata.
///
/// Returned by [`BytesView::slices()`] and provides each slice together with its
/// associated memory block metadata.
#[must_use]
#[derive(Debug)]
pub struct BytesViewSlices<'s> {
    view: &'s BytesView,

    // Index of the most recent that we have already returned.
    //
    // Index into spans_reversed, counting from the end (the logical first span).
    // Starts at spans_reversed.len() (one past the end) and counts down toward 0.
    previous_span_index: usize,
}

impl<'s> BytesViewSlices<'s> {
    pub(crate) fn new(view: &'s BytesView) -> Self {
        Self {
            view,
            previous_span_index: view.spans_reversed.len(),
        }
    }
}

impl<'s> Iterator for BytesViewSlices<'s> {
    type Item = (&'s [u8], Option<&'s dyn BlockMeta>);

    #[cfg_attr(test, mutants::skip)] // Mutating this can cause infinite loops.
    fn next(&mut self) -> Option<Self::Item> {
        if self.previous_span_index == 0 {
            return None;
        }

        self.previous_span_index -= 1;
        let span = &self.view.spans_reversed[self.previous_span_index];
        let slice: &'s [u8] = span;
        let meta: Option<&'s dyn BlockMeta> = span.block_ref().meta();

        Some((slice, meta))
    }
}

const SPAN_COUNT_BUCKETS: &[Magnitude] = &[0, 1, 2, 4, 8, 16, 32];

thread_local! {
    static VIEW_CREATED_SPANS: Event = Event::builder()
        .name("bytesbuf_view_created_spans")
        .histogram(SPAN_COUNT_BUCKETS)
        .build();
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    #![allow(
        clippy::indexing_slicing,
        clippy::needless_range_loop,
        clippy::arithmetic_side_effects,
        reason = "This is all fine in test code"
    )]

    use std::pin::pin;
    use std::thread;

    use new_zealand::nz;
    use static_assertions::{assert_impl_all, assert_not_impl_any};
    use testing_aids::assert_panic;

    use super::*;
    use crate::BytesBuf;
    use crate::mem::testing::{TestMemoryBlock, TransparentMemory, std_alloc_block};

    assert_impl_all!(BytesView: Send, Sync, Eq);

    // BytesView intentionally does not implement From<&[u8]> because creating a view
    // requires a memory provider to ensure optimal memory configuration. Users should
    // call `BytesView::copied_from_slice()` instead, which makes the memory provider
    // requirement explicit.
    assert_not_impl_any!(BytesView: From<&'static [u8]>);

    #[test]
    fn smoke_test() {
        let mut span_builder = std_alloc_block::allocate(nz!(10)).into_span_builder();

        span_builder.put_slice(&1234_u64.to_ne_bytes());
        span_builder.put_slice(&16_u16.to_ne_bytes());

        let span1 = span_builder.consume(nz!(4));
        let span2 = span_builder.consume(nz!(3));
        let span3 = span_builder.consume(nz!(3));

        assert_eq!(0, span_builder.remaining_capacity());
        assert_eq!(span1.len(), 4);
        assert_eq!(span2.len(), 3);
        assert_eq!(span3.len(), 3);

        let mut view = BytesView::from_spans(vec![span1, span2, span3]);

        assert!(!view.is_empty());
        assert_eq!(10, view.len());

        let slice = view.first_slice();
        assert_eq!(4, slice.len());

        // We read 8 bytes here, so should land straight inside span3.
        assert_eq!(view.get_num_ne::<u64>(), 1234);

        assert_eq!(2, view.len());

        let slice = view.first_slice();
        assert_eq!(2, slice.len());

        assert_eq!(view.get_num_ne::<u16>(), 16);

        assert_eq!(0, view.len());
        assert!(view.is_empty());
    }

    #[test]
    fn oob_is_panic() {
        let mut span_builder = std_alloc_block::allocate(nz!(10)).into_span_builder();

        span_builder.put_slice(&1234_u64.to_ne_bytes());
        span_builder.put_slice(&16_u16.to_ne_bytes());

        let span1 = span_builder.consume(nz!(4));
        let span2 = span_builder.consume(nz!(3));
        let span3 = span_builder.consume(nz!(3));

        let mut view = BytesView::from_spans(vec![span1, span2, span3]);

        assert_eq!(10, view.len());

        assert_eq!(view.get_num_ne::<u64>(), 1234);
        assert_panic!(_ = view.get_num_ne::<u32>()); // Reads 4 but only has 2 remaining.
    }

    #[test]
    fn extend_lifetime_references_all_blocks() {
        // We need to detect here whether a block is being released (i.e. ref count goes to zero).

        // SAFETY: We are not allowed to drop this until all BlockRef are gone. This is fine
        // because it is dropped at the end of the function, after all BlockRef instances.
        let block1 = unsafe { TestMemoryBlock::new(nz!(8), None) };
        let block1 = pin!(block1);

        // SAFETY: We are not allowed to drop this until all BlockRef are gone. This is fine
        // because it is dropped at the end of the function, after all BlockRef instances.
        let block2 = unsafe { TestMemoryBlock::new(nz!(8), None) };
        let block2 = pin!(block2);

        let guard = {
            // SAFETY: We guarantee exclusive access to the memory capacity.
            let mut span_builder1 = unsafe { block1.as_ref().to_block() }.into_span_builder();
            // SAFETY: We guarantee exclusive access to the memory capacity.
            let mut span_builder2 = unsafe { block2.as_ref().to_block() }.into_span_builder();

            span_builder1.put_slice(&1234_u64.to_ne_bytes());
            span_builder2.put_slice(&1234_u64.to_ne_bytes());

            let span1 = span_builder1.consume(nz!(8));
            let span2 = span_builder2.consume(nz!(8));

            let view = BytesView::from_spans(vec![span1, span2]);

            view.extend_lifetime()
        };

        // The sequence was destroyed and all BlockRefs it was holding are gone.
        // However, the lifetime guard is still alive and has a BlockRef.

        assert_eq!(block1.ref_count(), 1);
        assert_eq!(block2.ref_count(), 1);

        drop(guard);

        // And now they should all be dead.
        assert_eq!(block1.ref_count(), 0);
        assert_eq!(block2.ref_count(), 0);
    }

    #[test]
    fn from_views() {
        let mut span_builder = std_alloc_block::allocate(nz!(100)).into_span_builder();

        span_builder.put_slice(&1234_u64.to_ne_bytes());
        span_builder.put_slice(&5678_u64.to_ne_bytes());

        let span1 = span_builder.consume(nz!(8));
        let span2 = span_builder.consume(nz!(8));

        let view1 = BytesView::from_spans(vec![span1]);
        let view2 = BytesView::from_spans(vec![span2]);

        let mut combined_view = BytesView::from_views(vec![view1, view2]);

        assert_eq!(16, combined_view.len());

        assert_eq!(combined_view.get_num_ne::<u64>(), 1234);
        assert_eq!(combined_view.get_num_ne::<u64>(), 5678);
    }

    #[test]
    fn empty_view() {
        let view = BytesView::default();

        assert!(view.is_empty());
        assert_eq!(0, view.len());
        assert_eq!(0, view.first_slice().len());
    }

    #[test]
    fn slice_from_single_span_view() {
        // A very simple view to start with, consisting of just one 100 byte span.
        let span_builder = std_alloc_block::allocate(nz!(100)).into_span_builder();

        let mut buf = BytesBuf::from_span_builders([span_builder]);

        for i in 0..100 {
            buf.put_byte(i);
        }

        let view = buf.consume_all();

        let mut sliced_view = view.range(50..55);

        assert_eq!(5, sliced_view.len());
        assert_eq!(100, view.len());

        assert_eq!(50, sliced_view.get_byte());

        assert_eq!(4, sliced_view.len());
        assert_eq!(100, view.len());

        assert_eq!(51, sliced_view.get_byte());
        assert_eq!(52, sliced_view.get_byte());
        assert_eq!(53, sliced_view.get_byte());
        assert_eq!(54, sliced_view.get_byte());

        assert_eq!(0, sliced_view.len());

        assert!(view.range_checked(0..101).is_none());
        assert!(view.range_checked(100..101).is_none());
        assert!(view.range_checked(101..101).is_none());
    }

    #[test]
    fn slice_from_multi_span_view() {
        const SPAN_SIZE: NonZero<BlockSize> = nz!(10);

        // A multi-span view, 10 bytes x10.
        let span_builders = iter::repeat_with(|| std_alloc_block::allocate(SPAN_SIZE).into_span_builder())
            .take(10)
            .collect::<Vec<_>>();

        let mut buf = BytesBuf::from_span_builders(span_builders);

        for i in 0..100 {
            buf.put_byte(i);
        }

        let view = buf.consume_all();

        let mut first5 = view.range(0..5);
        assert_eq!(5, first5.len());
        assert_eq!(100, view.len());
        assert_eq!(0, first5.get_byte());

        let mut last5 = view.range(95..100);
        assert_eq!(5, last5.len());
        assert_eq!(100, view.len());
        assert_eq!(95, last5.get_byte());

        let mut middle5 = view.range(49..54);
        assert_eq!(5, middle5.len());
        assert_eq!(100, view.len());
        assert_eq!(49, middle5.get_byte());
        assert_eq!(50, middle5.get_byte());
        assert_eq!(51, middle5.get_byte());
        assert_eq!(52, middle5.get_byte());
        assert_eq!(53, middle5.get_byte());

        assert!(view.range_checked(0..101).is_none());
        assert!(view.range_checked(100..101).is_none());
        assert!(view.range_checked(101..101).is_none());
    }

    #[test]
    fn slice_indexing_kinds() {
        let span_builder = std_alloc_block::allocate(nz!(10)).into_span_builder();

        let mut buf = BytesBuf::from_span_builders([span_builder]);
        buf.put_byte(0);
        buf.put_byte(1);
        buf.put_byte(2);
        buf.put_byte(3);
        buf.put_byte(4);
        buf.put_byte(5);

        let data = buf.consume_all();

        let mut middle_four = data.range(1..5);
        assert_eq!(4, middle_four.len());
        assert_eq!(1, middle_four.get_byte());
        assert_eq!(2, middle_four.get_byte());
        assert_eq!(3, middle_four.get_byte());
        assert_eq!(4, middle_four.get_byte());

        let mut middle_four = data.range(1..=4);
        assert_eq!(4, middle_four.len());
        assert_eq!(1, middle_four.get_byte());
        assert_eq!(2, middle_four.get_byte());
        assert_eq!(3, middle_four.get_byte());
        assert_eq!(4, middle_four.get_byte());

        let mut last_two = data.range(4..);
        assert_eq!(2, last_two.len());
        assert_eq!(4, last_two.get_byte());
        assert_eq!(5, last_two.get_byte());

        let mut first_two = data.range(..2);
        assert_eq!(2, first_two.len());
        assert_eq!(0, first_two.get_byte());
        assert_eq!(1, first_two.get_byte());

        let mut first_two = data.range(..=1);
        assert_eq!(2, first_two.len());
        assert_eq!(0, first_two.get_byte());
        assert_eq!(1, first_two.get_byte());
    }

    #[test]
    fn slice_checked_with_excluded_start_bound() {
        let span_builder = std_alloc_block::allocate(nz!(100)).into_span_builder();

        let mut buf = BytesBuf::from_span_builders([span_builder]);
        buf.put_byte(0);
        buf.put_byte(1);
        buf.put_byte(2);
        buf.put_byte(3);
        buf.put_byte(4);
        buf.put_byte(5);
        buf.put_byte(6);
        buf.put_byte(7);
        buf.put_byte(8);

        let view = buf.consume_all();

        // Test with excluded start bound: (Bound::Excluded(1), Bound::Excluded(5))
        // This should be equivalent to 2..5 (items at indices 2, 3, 4)
        let sliced = view.range_checked((Bound::Excluded(1), Bound::Excluded(5)));
        assert!(sliced.is_some());
        let mut sliced = sliced.unwrap();
        assert_eq!(3, sliced.len());
        assert_eq!(2, sliced.get_byte());
        assert_eq!(3, sliced.get_byte());
        assert_eq!(4, sliced.get_byte());

        // Test edge case: excluded start at the last valid index returns empty sequence
        let sliced = view.range_checked((Bound::Excluded(8), Bound::Unbounded));
        assert!(sliced.is_some());
        assert_eq!(0, sliced.unwrap().len());

        // Test edge case: excluded start that would overflow when adding 1
        let sliced = view.range_checked((Bound::Excluded(usize::MAX), Bound::Unbounded));
        assert!(sliced.is_none());
    }

    #[test]
    fn slice_oob_is_panic() {
        let span_builder = std_alloc_block::allocate(nz!(1000)).into_span_builder();

        let mut buf = BytesBuf::from_span_builders([span_builder]);
        buf.put_byte_repeated(0, 100);

        let view = buf.consume_all();

        assert_panic!(_ = view.range(0..101));
        assert_panic!(_ = view.range(0..=100));
        assert_panic!(_ = view.range(100..=100));
        assert_panic!(_ = view.range(100..101));
        assert_panic!(_ = view.range(101..));
        assert_panic!(_ = view.range(101..101));
        assert_panic!(_ = view.range(101..=101));
    }

    #[test]
    fn slice_at_boundary_is_not_panic() {
        let span_builder = std_alloc_block::allocate(nz!(100)).into_span_builder();

        let mut buf = BytesBuf::from_span_builders([span_builder]);
        buf.put_byte_repeated(0, 100);

        let view = buf.consume_all();

        assert_eq!(0, view.range(0..0).len());
        assert_eq!(1, view.range(0..=0).len());
        assert_eq!(0, view.range(..0).len());
        assert_eq!(1, view.range(..=0).len());
        assert_eq!(0, view.range(100..100).len());
        assert_eq!(0, view.range(99..99).len());
        assert_eq!(1, view.range(99..=99).len());
        assert_eq!(1, view.range(99..).len());
        assert_eq!(100, view.range(..).len());
    }

    #[test]
    fn slice_empty_is_empty_if_not_oob() {
        let span_builder = std_alloc_block::allocate(nz!(100)).into_span_builder();

        let mut buf = BytesBuf::from_span_builders([span_builder]);

        for i in 0..100 {
            buf.put_byte(i);
        }

        let view = buf.consume_all();

        let sub_view = view.range(50..50);
        assert_eq!(0, sub_view.len());

        // 100 is the index at the end of the view - still in-bounds, if at edge.
        let sub_view = view.range(100..100);
        assert_eq!(0, sub_view.len());
        assert!(view.range_checked(101..101).is_none());
    }

    #[test]
    fn consume_all_slices() {
        const SPAN_SIZE: NonZero<BlockSize> = nz!(10);

        // A multi-span sequence, 10 bytes x10.
        let span_builders = iter::repeat_with(|| std_alloc_block::allocate(SPAN_SIZE).into_span_builder())
            .take(10)
            .collect::<Vec<_>>();

        let mut buf = BytesBuf::from_span_builders(span_builders);

        for i in 0..100 {
            buf.put_byte(i);
        }

        let mut view = buf.consume_all();

        let mut slice_index = 0;
        let mut bytes_consumed = 0;

        view.consume_all_slices(|slice| {
            assert_eq!(slice.len(), 10);
            bytes_consumed += slice.len();

            for i in 0..10 {
                assert_eq!(slice_index * 10 + i, slice[i] as usize);
            }

            slice_index += 1;
        });

        assert_eq!(bytes_consumed, 100);

        view.consume_all_slices(|_| unreachable!("view should now be empty"));
    }

    #[test]
    fn multithreaded_usage() {
        fn post_to_another_thread(view: BytesView) {
            thread::spawn(move || {
                let mut view = view;
                assert_eq!(view.get_byte(), b'H');
                assert_eq!(view.get_byte(), b'e');
                assert_eq!(view.get_byte(), b'l');
                assert_eq!(view.get_byte(), b'l');
                assert_eq!(view.get_byte(), b'o');
            })
            .join()
            .unwrap();
        }

        let memory = TransparentMemory::new();
        let view = BytesView::copied_from_slice(b"Hello, world!", &memory);

        post_to_another_thread(view);
    }

    #[test]
    fn slices_iterator() {
        let memory = TransparentMemory::new();
        let segment1 = BytesView::copied_from_slice(b"Hello, world!", &memory);
        let segment2 = BytesView::copied_from_slice(b"Hello, another world!", &memory);

        let view = BytesView::from_views(vec![segment1.clone(), segment2.clone()]);

        let slices: Vec<_> = view.slices().collect();

        assert_eq!(slices.len(), 2);
        assert_eq!(slices[0].0.len(), segment1.len());
        assert_eq!(slices[1].0.len(), segment2.len());
    }

    #[test]
    fn slices_iterator_empty() {
        let view = BytesView::new();
        assert_eq!(view.slices().count(), 0);
    }

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

        let view1 = BytesView::copied_from_slice(b"Hello, world!", &memory);
        let view2 = BytesView::copied_from_slice(b"Hello, world!", &memory);

        assert_eq!(view1, view2);

        let view3 = BytesView::copied_from_slice(b"Jello, world!", &memory);

        assert_ne!(view1, view3);

        let view4 = BytesView::copied_from_slice(b"Hello, world! ", &memory);

        assert_ne!(view1, view4);

        let view5_part1 = BytesView::copied_from_slice(b"Hello, ", &memory);
        let view5_part2 = BytesView::copied_from_slice(b"world!", &memory);
        let view5 = BytesView::from_views([view5_part1, view5_part2]);

        assert_eq!(view1, view5);
        assert_ne!(view5, view3);

        let view6 = BytesView::copied_from_slice(b"Hello, ", &memory);

        assert_ne!(view1, view6);
        assert_ne!(view5, view6);

        // Compare two multi-span views with misaligned span boundaries to exercise
        // span index advancement on both sides of the comparison.
        let view7_part1 = BytesView::copied_from_slice(b"Hel", &memory);
        let view7_part2 = BytesView::copied_from_slice(b"lo, world!", &memory);
        let view7 = BytesView::from_views([view7_part1, view7_part2]);

        assert_eq!(view5, view7);
        assert_eq!(view7, view5);
    }

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

        let view1 = BytesView::copied_from_slice(b"Hello, world!", &memory);

        assert_eq!(view1, b"Hello, world!".as_slice());
        assert_ne!(view1, b"Jello, world!".as_slice());
        assert_ne!(view1, b"Hello, world! ".as_slice());

        assert_eq!(b"Hello, world!".as_slice(), view1);
        assert_ne!(b"Jello, world!".as_slice(), view1);
        assert_ne!(b"Hello, world! ".as_slice(), view1);

        let view2_part1 = BytesView::copied_from_slice(b"Hello, ", &memory);
        let view2_part2 = BytesView::copied_from_slice(b"world!", &memory);
        let view2 = BytesView::from_views([view2_part1, view2_part2]);

        assert_eq!(view2, b"Hello, world!".as_slice());
        assert_ne!(view2, b"Jello, world!".as_slice());
        assert_ne!(view2, b"Hello, world! ".as_slice());
        assert_ne!(view2, b"Hello, ".as_slice());

        assert_eq!(b"Hello, world!".as_slice(), view2);
        assert_ne!(b"Jello, world!".as_slice(), view2);
        assert_ne!(b"Hello, world! ".as_slice(), view2);
        assert_ne!(b"Hello, ".as_slice(), view2);
    }

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

        let view1 = BytesView::copied_from_slice(b"Hello, world!", &memory);

        assert_eq!(view1, b"Hello, world!");
        assert_ne!(view1, b"Jello, world!");
        assert_ne!(view1, b"Hello, world! ");

        assert_eq!(b"Hello, world!", view1);
        assert_ne!(b"Jello, world!", view1);
        assert_ne!(b"Hello, world! ", view1);

        let view2_part1 = BytesView::copied_from_slice(b"Hello, ", &memory);
        let view2_part2 = BytesView::copied_from_slice(b"world!", &memory);
        let view2 = BytesView::from_views([view2_part1, view2_part2]);

        assert_eq!(view2, b"Hello, world!");
        assert_ne!(view2, b"Jello, world!");
        assert_ne!(view2, b"Hello, world! ");
        assert_ne!(view2, b"Hello, ");

        assert_eq!(b"Hello, world!", view2);
        assert_ne!(b"Jello, world!", view2);
        assert_ne!(b"Hello, world! ", view2);
        assert_ne!(b"Hello, ", view2);
    }

    #[test]
    fn first_slice_meta_empty_view() {
        let view = BytesView::new();
        assert!(view.first_slice_meta().is_none());
    }

    #[test]
    fn first_slice_meta_no_metadata() {
        let memory = TransparentMemory::new();
        let view = BytesView::copied_from_slice(b"Hello", &memory);
        // TransparentMemory does not attach metadata.
        assert!(view.first_slice_meta().is_none());
    }

    #[test]
    fn first_slice_meta_with_metadata() {
        #[derive(Debug)]
        struct TestMeta;
        impl BlockMeta for TestMeta {}

        // SAFETY: We are not allowed to drop this until all BlockRef are gone. This is fine
        // because it is dropped at the end of the function, after all BlockRef instances.
        let block = unsafe { TestMemoryBlock::new(nz!(100), Some(Box::new(TestMeta))) };
        let block = pin!(block);

        // SAFETY: We guarantee exclusive access to the memory capacity.
        let mut span_builder = unsafe { block.as_ref().to_block() }.into_span_builder();
        span_builder.put_slice(b"Hello");
        let span = span_builder.consume(nz!(5));

        let view = BytesView::from_spans(vec![span]);

        let meta = view.first_slice_meta();
        assert!(meta.is_some());
        assert!(meta.unwrap().is::<TestMeta>());
    }

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

        let view1 = BytesView::copied_from_slice(b"Hello, ", &memory);
        let view2 = BytesView::copied_from_slice(b"world!", &memory);

        let view = BytesView::from_views([view1, view2]);

        let mut slices_iter = view.slices();

        // We have two chunks, both without metadata.
        let (data1, meta1) = slices_iter.next().expect("should have first slice");
        assert!(!data1.is_empty());
        assert!(meta1.is_none());

        let (data2, meta2) = slices_iter.next().expect("should have second slice");
        assert!(!data2.is_empty());
        assert!(meta2.is_none());

        assert!(slices_iter.next().is_none());
    }

    #[test]
    fn meta_some() {
        #[derive(Debug)]
        struct GreenMeta;
        #[derive(Debug)]
        struct BlueMeta;

        impl BlockMeta for GreenMeta {}
        impl BlockMeta for BlueMeta {}

        // SAFETY: We are not allowed to drop this until all BlockRef are gone. This is fine
        // because it is dropped at the end of the function, after all BlockRef instances.
        let block1 = unsafe { TestMemoryBlock::new(nz!(100), Some(Box::new(GreenMeta {}))) };
        let block1 = pin!(block1);

        // SAFETY: We are not allowed to drop this until all BlockRef are gone. This is fine
        // because it is dropped at the end of the function, after all BlockRef instances.
        let block2 = unsafe { TestMemoryBlock::new(nz!(100), Some(Box::new(BlueMeta {}))) };
        let block2 = pin!(block2);

        // SAFETY: We guarantee exclusive access to the memory capacity.
        let block1 = unsafe { block1.as_ref().to_block() };
        // SAFETY: We guarantee exclusive access to the memory capacity.
        let block2 = unsafe { block2.as_ref().to_block() };

        let mut buf = BytesBuf::from_blocks([block1, block2]);

        // Add enough bytes to make use of both blocks.
        buf.put_byte_repeated(123, 166);

        let view = buf.consume_all();

        let mut slices_iter = view.slices();

        // NB! There is no requirement that the BytesBuf use the blocks in the order we gave
        // them in. We use white-box knowledge here to know that it actually reverses the order.
        // This behavior may change in a future version - be ready to change the test if so.

        let (data1, meta1) = slices_iter.next().expect("should have first block");
        assert!(!data1.is_empty());
        assert!(meta1.is_some());
        assert!(meta1.unwrap().is::<BlueMeta>());
        assert!(!meta1.unwrap().is::<GreenMeta>());

        let (data2, meta2) = slices_iter.next().expect("should have second block");
        assert!(!data2.is_empty());
        assert!(meta2.is_some());
        assert!(meta2.unwrap().is::<GreenMeta>());
        assert!(!meta2.unwrap().is::<BlueMeta>());

        assert!(slices_iter.next().is_none(), "should have no more slices");
    }

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

        // Create two single-span views.
        let mut view1 = BytesView::copied_from_slice(b"Hello, ", &memory);
        let view2 = BytesView::copied_from_slice(b"world!", &memory);

        assert_eq!(view1.len(), 7);
        assert_eq!(view2.len(), 6);

        view1.append(view2);

        assert_eq!(view1.len(), 13);
        assert_eq!(view1, b"Hello, world!");
    }

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

        // Create two multi-span views (2 spans each)
        let view1_part1 = BytesView::copied_from_slice(b"AAA", &memory);
        let view1_part2 = BytesView::copied_from_slice(b"BBB", &memory);
        let mut view1 = BytesView::from_views([view1_part1, view1_part2]);

        let view2_part1 = BytesView::copied_from_slice(b"CCC", &memory);
        let view2_part2 = BytesView::copied_from_slice(b"DDD", &memory);
        let view2 = BytesView::from_views([view2_part1, view2_part2]);

        assert_eq!(view1.len(), 6);
        assert_eq!(view2.len(), 6);

        view1.append(view2);

        assert_eq!(view1.len(), 12);
        assert_eq!(view1, b"AAABBBCCCDDD");
    }

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

        let mut view1 = BytesView::copied_from_slice(b"Hello", &memory);
        let view2 = BytesView::new();

        view1.append(view2);
        assert_eq!(view1.len(), 5);
        assert_eq!(view1, b"Hello");

        let mut view3 = BytesView::new();
        let view4 = BytesView::copied_from_slice(b"world", &memory);

        view3.append(view4);
        assert_eq!(view3.len(), 5);
        assert_eq!(view3, b"world");
    }

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

        // Create two single-span views
        let view1 = BytesView::copied_from_slice(b"Hello, ", &memory);
        let view2 = BytesView::copied_from_slice(b"world!", &memory);

        assert_eq!(view1.len(), 7);
        assert_eq!(view2.len(), 6);

        let view3 = view1.concat(view2);

        // Original view unchanged
        assert_eq!(view1.len(), 7);
        assert_eq!(view1, b"Hello, ");

        // New view contains combined data
        assert_eq!(view3.len(), 13);
        assert_eq!(view3, b"Hello, world!");
    }

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

        // Create two multi-span views (2 spans each)
        let view1_part1 = BytesView::copied_from_slice(b"AAA", &memory);
        let view1_part2 = BytesView::copied_from_slice(b"BBB", &memory);
        let view1 = BytesView::from_views([view1_part1, view1_part2]);

        let view2_part1 = BytesView::copied_from_slice(b"CCC", &memory);
        let view2_part2 = BytesView::copied_from_slice(b"DDD", &memory);
        let view2 = BytesView::from_views([view2_part1, view2_part2]);

        assert_eq!(view1.len(), 6);
        assert_eq!(view2.len(), 6);

        let view3 = view1.concat(view2);

        // Original view unchanged
        assert_eq!(view1.len(), 6);
        assert_eq!(view1, b"AAABBB");

        // New view contains combined data
        assert_eq!(view3.len(), 12);
        assert_eq!(view3, b"AAABBBCCCDDD");
    }

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

        let view1 = BytesView::copied_from_slice(b"Hello", &memory);
        let view2 = BytesView::new();

        let view3 = view1.concat(view2);
        assert_eq!(view3.len(), 5);
        assert_eq!(view3, b"Hello");

        let view4 = BytesView::new();
        let view5 = BytesView::copied_from_slice(b"world", &memory);

        let view6 = view4.concat(view5);
        assert_eq!(view6.len(), 5);
        assert_eq!(view6, b"world");
    }

    #[test]
    fn size_change_detector() {
        // The point of this is not to say that we expect it to have a specific size but to allow
        // us to easily detect when the size changes and (if we choose to) bless the change.
        // We assume 64-bit pointers - any support for 32-bit is problem for the future.
        assert_eq!(size_of::<BytesView>(), 272);
    }
}