ntex-bytes 1.15.1

Types and traits for working with bytes (bytes crate fork)
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
#![allow(clippy::op_ref, unused_must_use)]
use std::{borrow::Borrow, borrow::BorrowMut};

use ntex_bytes::info::Kind;
use ntex_bytes::{Buf, BufMut, BytePage, BytePageSize, Bytes, BytesMut, METADATA_SIZE};

const LONG: &[u8] = b"mary had a little lamb, little lamb, little lamb";
const SHORT: &[u8] = b"hello world";

fn inline_cap() -> usize {
    use std::mem;
    3 * mem::size_of::<usize>() - 1
}

fn is_sync<T: Sync>() {}
fn is_send<T: Send>() {}

/// STATEMENT: Byte containers have compact 64-bit layouts and a 23-byte zero payload can be stored inline inside `Option`.
///
/// HOW:
/// - Check container, metadata, pointer, and `Arc` sizes, accounting for the `tracker` feature's metadata layout.
/// - Freeze 23 zero bytes, verify inline storage, wrap in `Some`, and compare the preserved payload.
#[cfg(target_pointer_width = "64")]
#[test]
fn test_size() {
    assert_eq!(24, std::mem::size_of::<Bytes>());
    assert_eq!(24, std::mem::size_of::<Option<Bytes>>());
    #[cfg(not(feature = "tracker"))]
    assert_eq!(16, ntex_bytes::METADATA_SIZE);
    #[cfg(feature = "tracker")]
    assert_eq!(32, ntex_bytes::METADATA_SIZE);
    assert_eq!(8, std::mem::size_of::<BytesMut>());
    assert_eq!(16, std::mem::size_of::<ntex_bytes::BytePages>());
    assert_eq!(32, std::mem::size_of::<BytePage>());
    assert_eq!(16, std::mem::size_of::<std::sync::Arc<str>>());
    assert_eq!(8, std::mem::size_of::<std::sync::Arc<String>>());
    assert_eq!(16, std::mem::size_of::<&'static str>());

    let mut t = BytesMut::new();
    t.extend_from_slice(&b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"[..]);

    let val = t.freeze();
    assert!(val.is_inline());

    let val = Some(val);
    assert!(val.is_some());
    assert_eq!(
        val.as_ref().unwrap(),
        &b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"[..]
    )
}

/// STATEMENT: Both immutable and mutable byte buffers implement `Send` and `Sync`.
///
/// HOW:
/// - Instantiate the `is_send` and `is_sync` compile-time trait checks for `Bytes` and `BytesMut`.
#[test]
fn test_bounds() {
    is_sync::<Bytes>();
    is_sync::<BytesMut>();
    is_send::<Bytes>();
    is_send::<BytesMut>();
}

/// STATEMENT: Slice construction preserves content and supports equality with slices and vectors in both directions.
///
/// HOW:
/// - Construct `Bytes` and `BytesMut` from `abcdefgh` and compare against matching slice and vector representations.
#[test]
fn from_slice() {
    let a = Bytes::from(&b"abcdefgh"[..]);
    assert_eq!(a, b"abcdefgh"[..]);
    assert_eq!(a, &b"abcdefgh"[..]);
    assert_eq!(a, Vec::from(&b"abcdefgh"[..]));
    assert_eq!(b"abcdefgh"[..], a);
    assert_eq!(&b"abcdefgh"[..], a);
    assert_eq!(Vec::from(&b"abcdefgh"[..]), a);

    let a = BytesMut::copy_from_slice(&b"abcdefgh"[..]);
    assert_eq!(a, b"abcdefgh"[..]);
    assert_eq!(a, &b"abcdefgh"[..]);
    assert_eq!(b"abcdefgh"[..], a);
    assert_eq!(&b"abcdefgh"[..], a);
    assert_eq!(Vec::from(&b"abcdefgh"[..]), a);
}

/// STATEMENT: Immutable and mutable buffer debug formatting uses the same byte-string notation.
///
/// HOW:
/// - Debug-format `Bytes` and `BytesMut` containing `abcdefg` and compare each with `b"abcdefg"`.
#[test]
fn fmt() {
    let a = format!("{:?}", Bytes::from(&b"abcdefg"[..]));
    let b = "b\"abcdefg\"";

    assert_eq!(a, b);

    let a = format!("{:?}", BytesMut::copy_from_slice(&b"abcdefg"[..]));
    assert_eq!(a, b);
}

/// STATEMENT: Mutating a cloned mutable buffer leaves the original bytes unchanged.
///
/// HOW:
/// - Clone `hello`, overwrite the clone's first byte with `x`, and verify the source still equals `hello`.
#[test]
fn clone_mut() {
    let buf1 = BytesMut::from("hello");

    let mut buf2 = buf1.clone();
    buf2[0] = b'x';

    assert_eq!(buf1, "hello");
}

/// STATEMENT: Formatted writes append the same bytes whether supplied in one string or consecutive fragments.
///
/// HOW:
/// - Write a repeated string's first 64 bytes into capacity-64 buffers in one call and two 32-byte calls, then compare contents.
#[allow(clippy::sliced_string_as_bytes)]
#[test]
fn fmt_write() {
    use std::fmt::Write;
    let s = String::from_iter((0..10).map(|_| "abcdefg"));

    let mut a = BytesMut::with_capacity(64);
    write!(a, "{}", &s[..64]).unwrap();
    assert_eq!(a, s[..64].as_bytes());

    let mut b = BytesMut::with_capacity(64);
    write!(b, "{}", &s[..32]).unwrap();
    write!(b, "{}", &s[32..64]).unwrap();
    assert_eq!(b, s[..64].as_bytes());
}

/// STATEMENT: `BytesMut` supports stream writes and flushing.
///
/// HOW:
/// - Write `abcdefg` through `io::Write`, check the returned length and buffer contents, and unwrap a successful flush.
#[allow(clippy::sliced_string_as_bytes)]
#[test]
fn fmt_io_write() {
    use std::io::Write;

    let mut a = BytesMut::new();
    assert_eq!(a.write(b"abcdefg").unwrap(), 7);
    assert_eq!(&a, b"abcdefg");

    a.flush().unwrap();
}

/// STATEMENT: Copied byte buffers report their payload length and recognize empty input.
///
/// HOW:
/// - Construct `Bytes` and `BytesMut` from `abcdefg` and empty slices, checking length seven and empty status respectively.
#[test]
fn len() {
    let a = Bytes::from(&b"abcdefg"[..]);
    assert_eq!(a.len(), 7);

    let a = BytesMut::copy_from_slice(&b"abcdefg"[..]);
    assert_eq!(a.len(), 7);

    let a = Bytes::from(&b""[..]);
    assert!(a.is_empty());

    let a = BytesMut::copy_from_slice(&b""[..]);
    assert!(a.is_empty());
}

/// STATEMENT: Short owned strings and short split prefixes use inline immutable storage.
///
/// HOW:
/// - Convert `abcdefg` and an empty owned string, checking inline kind and emptiness.
/// - Freeze 35 bytes, split an eight-byte prefix, and verify the prefix is inline.
#[test]
fn inline() {
    let a = Bytes::from("abcdefg".to_string());
    assert!(a.is_inline());
    assert!(a.info().kind == Kind::Inline);

    let a = Bytes::from("".to_string());
    assert!(a.is_empty());

    let mut a = BytesMut::copy_from_slice(vec![b'*'; 35]).freeze();
    let b = a.split_to(8);
    assert!(b.is_inline());
}

/// STATEMENT: Range indexing exposes matching slices for immutable and mutable byte buffers.
///
/// HOW:
/// - Construct `hello world` via immutable and two mutable conversion paths and compare each `0..5` range with `hello`.
#[test]
fn index() {
    let a = Bytes::from(&b"hello world"[..]);
    assert_eq!(a[0..5], *b"hello");

    let a = BytesMut::from(&b"hello world"[..]);
    assert_eq!(a[0..5], *b"hello");

    let a = BytesMut::copy_from_slice(&b"hello world"[..]);
    assert_eq!(a[0..5], *b"hello");
}

/// STATEMENT: `Bytes::slice` handles full, partial, inclusive, unbounded, and empty ranges correctly.
///
/// HOW:
/// - Slice `hello world` using each range form, including empty ranges at the start, middle, and end, and compare expected substrings.
#[test]
fn slice() {
    let a = Bytes::from(&b"hello world"[..]);

    let b = a.slice(..);
    assert_eq!(b, b"hello world");

    let b = a.slice(3..5);
    assert_eq!(b, b"lo"[..]);

    let b = a.slice(3..=5);
    assert_eq!(b, b"lo "[..]);

    let b = a.slice(0..0);
    assert_eq!(b, b""[..]);

    let b = a.slice(3..3);
    assert_eq!(b, b""[..]);

    let b = a.slice(a.len()..a.len());
    assert_eq!(b, b""[..]);

    let b = a.slice(..5);
    assert_eq!(b, b"hello"[..]);

    let b = a.slice(3..);
    assert_eq!(b, b"lo world"[..]);
}

/// STATEMENT: Slicing with an end beyond the visible bytes panics.
///
/// HOW:
/// - Slice `hello world` from five through `inline_cap() + 1` and require a bounds panic.
#[test]
#[should_panic]
fn slice_oob_1() {
    let a = Bytes::from(&b"hello world"[..]);
    a.slice(5..(inline_cap() + 1));
}

/// STATEMENT: Slicing with a range entirely beyond visible bytes panics.
///
/// HOW:
/// - Slice `hello world` from `inline_cap() + 1` through `inline_cap() + 5` and require a bounds panic.
#[test]
#[should_panic]
fn slice_oob_2() {
    let a = Bytes::from(&b"hello world"[..]);
    a.slice((inline_cap() + 1)..(inline_cap() + 5));
}

/// STATEMENT: `split_off` returns a suffix and retains the prefix in the original buffer.
///
/// HOW:
/// - Split `helloworld` at five and compare the original with `hello` and the returned bytes with `world`.
#[test]
fn split_off() {
    let mut hello = Bytes::from(&b"helloworld"[..]);
    let world = hello.split_off(5);

    assert_eq!(hello, &b"hello"[..]);
    assert_eq!(world, &b"world"[..]);
}

/// STATEMENT: Splitting off beyond immutable-buffer length panics.
///
/// HOW:
/// - Call `split_off(inline_cap() + 1)` on `helloworld` and expect a bounds panic.
#[test]
#[should_panic]
fn split_off_oob() {
    let mut hello = Bytes::from(&b"helloworld"[..]);
    hello.split_off(inline_cap() + 1);
}

const MIN_CAPACITY: usize = 128 - METADATA_SIZE;

const B: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

/// STATEMENT: Splitting at any valid offset partitions copied and vector-backed bytes without losing data.
///
/// HOW:
/// - For every offset in `B`, call `split_off` and `split_to` on slice- and vector-created buffers.
/// - Check the relevant prefix length and concatenate both halves to recover `B` exactly.
#[test]
fn split_off_to_loop() {
    for i in 0..(B.len() + 1) {
        {
            let mut bytes = Bytes::from(B);
            let off = bytes.split_off(i);
            assert_eq!(i, bytes.len());
            let mut sum: Vec<u8> = Vec::new();
            sum.extend(bytes.iter());
            sum.extend(off.iter());
            assert_eq!(B, &sum[..]);
        }
        {
            let mut bytes = Bytes::from(B.to_vec());
            let off = bytes.split_off(i);
            assert_eq!(i, bytes.len());
            let mut sum: Vec<u8> = Vec::new();
            sum.extend(bytes.iter());
            sum.extend(off.iter());
            assert_eq!(B, &sum[..]);
        }
        {
            let mut bytes = Bytes::from(B);
            let off = bytes.split_to(i);
            assert_eq!(i, off.len());
            let mut sum: Vec<u8> = Vec::new();
            sum.extend(off.iter());
            sum.extend(bytes.iter());
            assert_eq!(B, &sum[..]);
        }
        {
            let mut bytes = Bytes::from(B.to_vec());
            let off = bytes.split_to(i);
            assert_eq!(i, off.len());
            let mut sum: Vec<u8> = Vec::new();
            sum.extend(off.iter());
            sum.extend(bytes.iter());
            assert_eq!(B, &sum[..]);
        }
    }
}

/// STATEMENT: Prefix splitting returns the requested bytes across inline, vector-backed, and mutable storage.
///
/// HOW:
/// - Split `SHORT` at four and `LONG` at four or thirty using immutable and mutable buffers, checking returned prefixes and retained suffixes.
#[test]
fn split_to_1() {
    // Inline
    let mut a = Bytes::from(SHORT);
    let b = a.split_to(4);

    assert_eq!(SHORT[4..], a);
    assert_eq!(SHORT[..4], b);

    // Allocated
    let mut a = Bytes::from(Vec::from(LONG));
    let b = a.split_to(4);

    assert_eq!(LONG[4..], a);
    assert_eq!(LONG[..4], b);

    let mut a = Bytes::from(Vec::from(LONG));
    let b = a.split_to(30);

    assert_eq!(LONG[30..], a);
    assert_eq!(LONG[..30], b);

    // bytes vec
    let mut a = BytesMut::copy_from_slice(LONG);
    let b = a.split_to(4);

    assert_eq!(LONG[4..], a);
    assert_eq!(LONG[..4], b);

    let mut a = BytesMut::copy_from_slice(LONG);
    let b = a.split_to(30);

    assert_eq!(LONG[30..], a);
    assert_eq!(LONG[..30], b);
}

/// STATEMENT: Dropping a split prefix does not invalidate the remaining immutable or mutable buffer.
///
/// HOW:
/// - Construct both buffer types from `LONG`, split one byte, compare each remainder with `LONG[1..]`, and drop the prefix.
#[test]
fn split_to_2() {
    let mut a = Bytes::from(LONG);
    assert_eq!(LONG, a);

    let b = a.split_to(1);

    assert_eq!(LONG[1..], a);
    drop(b);

    let mut a = BytesMut::copy_from_slice(LONG);
    assert_eq!(LONG, a);

    let b = a.split_to(1);

    assert_eq!(LONG[1..], a);
    drop(b);
}

/// STATEMENT: Prefix splitting beyond immutable-buffer length panics.
///
/// HOW:
/// - Call `split_to(inline_cap() + 1)` on immutable `helloworld` and expect a bounds panic.
#[test]
#[should_panic]
fn split_to_oob() {
    let mut hello = Bytes::from(&b"helloworld"[..]);
    hello.split_to(inline_cap() + 1);
}

/// STATEMENT: Prefix splitting beyond mutable-buffer length panics.
///
/// HOW:
/// - Copy `helloworld` into `BytesMut`, split at `inline_cap() + 1`, and expect a bounds panic.
#[test]
#[should_panic]
fn split_to_oob_mut() {
    let mut hello = BytesMut::copy_from_slice(&b"helloworld"[..]);
    hello.split_to(inline_cap() + 1);
}

/// STATEMENT: Reserved but uninitialized capacity cannot be exposed by prefix splitting.
///
/// HOW:
/// - Allocate an empty capacity-1,024 mutable buffer, call `split_to(128)`, and expect a panic despite sufficient allocation capacity.
#[test]
#[should_panic]
fn split_to_uninitialized() {
    let mut bytes = BytesMut::with_capacity(1024);
    let _other = bytes.split_to(128);
}

/// STATEMENT: Immutable splitting validates initialized length rather than spare allocation capacity.
///
/// HOW:
/// - Freeze four bytes in a capacity-100 buffer and confirm both split methods accept offset four.
/// - Catch and verify panics from both methods at offset five.
#[test]
fn split_off_to_at_gt_len() {
    fn make_bytes() -> Bytes {
        let mut bytes = BytesMut::with_capacity(100);
        bytes.put_slice(&[10, 20, 30, 40]);
        bytes.freeze()
    }

    use std::panic;

    make_bytes().split_to(4);
    make_bytes().split_off(4);

    assert!(
        panic::catch_unwind(move || {
            make_bytes().split_to(5);
        })
        .is_err()
    );

    assert!(
        panic::catch_unwind(move || {
            make_bytes().split_off(5);
        })
        .is_err()
    );
}

/// STATEMENT: `Bytes` supports content-based borrowing, ordering, equality, iteration, and shared-allocation metadata.
///
/// HOW:
/// - Compare `hello world` against strings, slices, arrays, vectors, and mutable buffers, and check ordering against `g`.
/// - Clone vector-backed `B` and check reference counts and capacity; collect through iterator forms, truncate to `hello`, and clear.
#[test]
#[allow(
    clippy::byte_char_slices,
    clippy::cmp_owned,
    clippy::redundant_slicing,
    clippy::iter_cloned_collect,
    clippy::needless_borrow
)]
fn fns_defined_for_bytes() {
    let bytes = Bytes::from(&b"hello world"[..]);
    let _ = bytes.as_ptr();
    assert_eq!(Borrow::<[u8]>::borrow(&bytes), b"hello world");

    let bytes = Bytes::from(b"hello world");
    assert_eq!(bytes, "hello world");
    assert_eq!(bytes, b"hello world");

    assert!(bytes > "g");
    assert!(bytes > b"g");
    assert!(bytes > [b'g']);
    assert!(bytes > &[b'g'][..]);
    assert!(bytes > "g".to_string());
    assert!(bytes > "g".as_bytes().to_vec());
    assert!(bytes > Bytes::from("g"));
    assert!("g" < bytes);
    assert!("g".to_string() < bytes);
    assert!("g".as_bytes().to_vec() < bytes);
    assert!([b'g'] < bytes);
    assert!(Bytes::from(&"g"[..]) < bytes);

    assert_eq!(bytes, "hello world");
    assert_eq!(bytes, "hello world".as_bytes().to_vec());
    assert_eq!(bytes, "hello world".to_string());
    assert_eq!(bytes, b"hello world");
    assert_eq!(bytes, &"hello world"[..]);
    assert_eq!(bytes, BytesMut::copy_from_slice(b"hello world"));
    assert_eq!(&bytes[..], b"hello world");
    assert_eq!(bytes.as_ref(), b"hello world");
    assert_eq!("hello world", bytes);
    assert_eq!("hello world".as_bytes().to_vec(), bytes);
    assert_eq!("hello world".to_string(), bytes);
    assert_eq!(b"hello world", bytes);
    assert_eq!(&"hello world"[..], bytes);
    assert_eq!(
        bytes,
        [
            b'h', b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd'
        ]
    );
    assert_eq!(
        [
            b'h', b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd'
        ],
        bytes,
    );

    let bytes = Bytes::copy_from_slice(&B[..]);
    assert_eq!(bytes.info().kind, Kind::Vec);
    assert_eq!(bytes.info().refs, 1);
    assert_eq!(bytes.info().capacity, B.len() + METADATA_SIZE);
    let b2 = bytes.clone();
    assert_eq!(b2.info().kind, Kind::Vec);
    assert_eq!(b2.info().refs, 2);
    assert_eq!(b2.info().capacity, B.len() + METADATA_SIZE);
    drop(b2);
    assert_eq!(bytes.info().kind, Kind::Vec);
    assert_eq!(bytes.info().refs, 1);
    assert_eq!(bytes.info().capacity, B.len() + METADATA_SIZE);

    let mut bytes = Bytes::from(&b"hello world"[..]);

    // Iterator
    let v: Vec<u8> = (&bytes).iter().cloned().collect();
    assert_eq!(&v[..], bytes);

    let v: Vec<u8> = bytes.as_ref().iter().cloned().collect();
    assert_eq!(&v[..], bytes);

    let v: Vec<u8> = bytes.clone().into_iter().collect();
    assert_eq!(&v[..], bytes);

    let v: Vec<u8> = (&bytes).into_iter().cloned().collect();
    assert_eq!(&v[..], bytes);

    let b2: Bytes = v.iter().collect();
    assert_eq!(b2, bytes);
    assert_eq!(&v[..], b2);

    bytes.truncate(5);
    assert_eq!(bytes, b"hello"[..]);

    bytes.clear();
    assert!(bytes.is_empty());
}

/// STATEMENT: `BytesMut` supports mutable borrowing, content comparisons, iteration, resizing, and explicit visible lengths.
///
/// HOW:
/// - Borrow and compare `hello world` across string and byte containers and collect through borrowed and owned iterators.
/// - Truncate, clear, resize with `1`, mutate the first byte, and set another buffer's length to one, checking each resulting payload.
#[test]
#[allow(clippy::redundant_slicing)]
fn fns_defined_for_bytes_vec() {
    // BytesMut
    let mut bytes = BytesMut::copy_from_slice(&b"hello world"[..]);
    let _ = bytes.as_ptr();
    let _ = bytes.as_mut_ptr();
    assert_eq!(Borrow::<[u8]>::borrow(&bytes), b"hello world");
    assert_eq!(BorrowMut::<[u8]>::borrow_mut(&mut bytes), b"hello world");

    let mut bytes = BytesMut::copy_from_slice(b"hello world");
    assert_eq!(Borrow::<[u8]>::borrow(&bytes), b"hello world");
    assert_eq!(BorrowMut::<[u8]>::borrow_mut(&mut bytes), b"hello world");

    assert_eq!(bytes, "hello world");
    assert_eq!(bytes, "hello world".as_bytes().to_vec());
    assert_eq!(bytes, "hello world".to_string());
    assert_eq!(bytes, b"hello world");
    assert_eq!(bytes, &"hello world"[..]);
    assert_eq!(bytes, Bytes::copy_from_slice(b"hello world"));
    assert_eq!(&bytes[..], b"hello world");
    assert_eq!(
        bytes,
        [
            b'h', b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd'
        ]
    );
    assert_eq!("hello world", bytes);
    assert_eq!("hello world".as_bytes().to_vec(), bytes);
    assert_eq!("hello world".to_string(), bytes);
    assert_eq!(b"hello world", bytes);
    assert_eq!(
        [
            b'h', b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd'
        ],
        bytes
    );

    // Iterator
    let v: Vec<u8> = bytes.iter().cloned().collect();
    assert_eq!(&v[..], bytes);

    let v: Vec<u8> = bytes.as_ref().to_vec();
    assert_eq!(&v[..], bytes);

    let v: Vec<u8> = bytes.iter().cloned().collect();
    assert_eq!(&v[..], bytes);

    let v: Vec<u8> = (&bytes).into_iter().cloned().collect();
    assert_eq!(&v[..], bytes);

    let v: Vec<u8> = bytes.into_iter().collect();

    let mut bytes = BytesMut::copy_from_slice(b"hello world");
    assert_eq!(&v[..], bytes);

    let b2: BytesMut = v.iter().collect();
    assert_eq!(b2, bytes);
    assert_eq!(&v[..], b2);

    bytes.truncate(5);
    assert_eq!(bytes, b"hello"[..]);

    bytes.clear();
    assert!(bytes.is_empty());

    bytes.resize(10, b'1');
    assert_eq!(bytes, b"1111111111"[..]);

    assert_eq!(bytes.remaining(), 10);
    assert_eq!(bytes.chunk(), &b"1111111111"[..]);

    bytes.as_mut()[0] = b'2';
    assert_eq!(bytes, b"2111111111"[..]);

    let mut bytes = BytesMut::copy_from_slice(b"hello world");
    // SAFETY: The initialized buffer contains the one-byte prefix being retained.
    unsafe { bytes.set_len(1) };
    assert_eq!(bytes, "h");
}

/// STATEMENT: Reserving additional capacity for copied mutable bytes preserves their existing length contribution.
///
/// HOW:
/// - Copy `LONG`, reserve 64 additional bytes, and check capacity equals `LONG.len() + 64`.
#[test]
fn reserve_convert() {
    // Vec -> Vec
    let mut bytes = BytesMut::copy_from_slice(LONG);
    bytes.reserve(64);
    assert_eq!(bytes.capacity(), LONG.len() + 64);
}

/// STATEMENT: Reservation after consuming front bytes sizes the visible capacity for remaining data and requested space.
///
/// HOW:
/// - Fill capacity 16, advance ten bytes, check remaining capacity six, reserve 32, and verify capacity 38.
#[test]
fn reserve_recycling() {
    let mut bytes = BytesMut::with_capacity(16);
    assert_eq!(bytes.capacity(), 16);
    bytes.put("0123456789012345".as_bytes());
    bytes.advance(10);
    assert_eq!(bytes.capacity(), 6);
    bytes.reserve(32);
    assert_eq!(bytes.capacity(), 38);
}

/// STATEMENT: Extending an initially zero-capacity mutable buffer grows it to hold an iterator's bytes.
///
/// HOW:
/// - Call `extend` with `LONG` on `BytesMut::with_capacity(0)` and compare the complete contents with `LONG`.
#[test]
fn extend_mut() {
    let mut bytes = BytesMut::with_capacity(0);
    bytes.extend(LONG);
    assert_eq!(*bytes, LONG[..]);
}

/// STATEMENT: Consecutive slice extensions preserve byte order across short and longer first fragments.
///
/// HOW:
/// - Split `LONG` at offsets three and 34, append both fragments into fresh mutable buffers, and compare each result with `LONG`.
#[test]
fn extend_from_slice_mut() {
    for &i in &[3, 34] {
        let mut bytes = BytesMut::new();
        bytes.extend_from_slice(&LONG[..i]);
        bytes.extend_from_slice(&LONG[i..]);
        assert_eq!(LONG[..], *bytes);
    }
}

/// STATEMENT: Static byte storage supports splitting into the expected prefix and suffix.
///
/// HOW:
/// - Construct static `ab`, split off at one, and verify retained `a` and returned `b`.
#[test]
fn from_static() {
    let mut a = Bytes::from_static(b"ab");
    let b = a.split_off(1);

    assert_eq!(a, b"a"[..]);
    assert_eq!(b, b"b"[..]);
}

/// STATEMENT: Advancing short copied immutable bytes leaves the correct suffix.
///
/// HOW:
/// - Construct `Bytes` from the `hello world` slice, advance six bytes, and compare with `world`.
#[test]
fn advance_inline() {
    let mut a = Bytes::from(&b"hello world"[..]);
    a.advance(6);
    assert_eq!(a, &b"world"[..]);
}

/// STATEMENT: Advancing static immutable bytes leaves the correct suffix.
///
/// HOW:
/// - Construct static `hello world`, advance six bytes, and compare with `world`.
#[test]
fn advance_static() {
    let mut a = Bytes::from_static(b"hello world");
    a.advance(6);
    assert_eq!(a, &b"world"[..]);
}

/// STATEMENT: Mutable-buffer advancement and later reservation preserve the remaining suffix.
///
/// HOW:
/// - Advance a long copied sentence by 16 and four bytes, check each suffix, reserve 1,024 bytes, and check contents again.
/// - Advance another six bytes and compare the final suffix.
#[test]
fn advance_vec() {
    let mut a = BytesMut::copy_from_slice(b"hello world boooo yah world zomg wat wat");
    a.advance(16);
    assert_eq!(a, b"o yah world zomg wat wat"[..]);

    a.advance(4);
    assert_eq!(a, b"h world zomg wat wat"[..]);

    // Reserve some space.
    a.reserve(1024);
    assert_eq!(a, b"h world zomg wat wat"[..]);

    a.advance(6);
    assert_eq!(a, b"d zomg wat wat"[..]);
}

/// STATEMENT: Advancing mutable bytes beyond their visible length panics.
///
/// HOW:
/// - Copy `hello world`, advance twenty bytes, and require a bounds panic.
#[test]
#[should_panic]
fn advance_past_len_vec() {
    let mut a = BytesMut::copy_from_slice(b"hello world");
    a.advance(20);
}

/// STATEMENT: Equality between immutable and mutable byte buffers compares contents symmetrically.
///
/// HOW:
/// - Compare matching `The quick red fox` buffers in both directions, then compare a different immutable sentence with the mutable buffer.
#[test]
fn partial_eq_bytesvec() {
    let bytes = Bytes::from(&b"The quick red fox"[..]);
    let bytesmut = BytesMut::copy_from_slice(&b"The quick red fox"[..]);
    assert!(bytes == bytesmut);
    assert!(bytesmut == bytes);
    let bytes2 = Bytes::from(&b"Jumped over the lazy brown dog"[..]);
    assert!(bytes2 != bytesmut);
    assert!(bytesmut != bytes2);
}

/// STATEMENT: Collecting bytes works for an iterator without an exact size hint.
///
/// HOW:
/// - Scan a repeated `x` iterator down to 100 items while recording expected bytes, collect into `Bytes`, and compare both payloads.
#[test]
fn from_iter_no_size_hint() {
    use std::iter;

    let mut expect = vec![];

    let actual: Bytes = iter::repeat(b'x')
        .scan(100, |cnt, item| {
            if *cnt >= 1 {
                *cnt -= 1;
                expect.push(item);
                Some(item)
            } else {
                None
            }
        })
        .collect();

    assert_eq!(&actual[..], &expect[..]);
}

fn test_slice_ref(bytes: &Bytes, start: usize, end: usize, expected: &[u8]) {
    let slice = &(bytes.as_ref()[start..end]);
    let sub = bytes.slice_ref(slice);
    assert_eq!(&sub[..], expected);
}

/// STATEMENT: `slice_ref` returns matching bytes for borrowed subranges, including empty boundary ranges.
///
/// HOW:
/// - Borrow five ranges from `012345678`, pass them through `slice_ref`, and compare empty, prefix, middle, and suffix results.
#[test]
fn slice_ref_works() {
    let bytes = Bytes::from(&b"012345678"[..]);

    test_slice_ref(&bytes, 0, 0, b"");
    test_slice_ref(&bytes, 0, 3, b"012");
    test_slice_ref(&bytes, 2, 6, b"2345");
    test_slice_ref(&bytes, 7, 9, b"78");
    test_slice_ref(&bytes, 9, 9, b"");
}

/// STATEMENT: `slice_ref` accepts an empty subrange borrowed from an empty buffer itself.
///
/// HOW:
/// - Borrow `0..0` from empty `Bytes`, construct its referenced slice, and verify the result is empty.
#[test]
fn slice_ref_empty() {
    let bytes = Bytes::from(&b""[..]);
    let slice = &(bytes.as_ref()[0..0]);

    let sub = bytes.slice_ref(slice);
    assert_eq!(&sub[..], b"");
}

/// STATEMENT: `slice_ref` rejects a matching-looking slice from unrelated storage.
///
/// HOW:
/// - Pass four bytes borrowed from a separate literal to `slice_ref` on `012345678` and expect a panic.
#[test]
#[should_panic]
fn slice_ref_catches_not_a_subset() {
    let bytes = Bytes::from(&b"012345678"[..]);
    let slice = &b"012345"[0..4];

    bytes.slice_ref(slice);
}

/// STATEMENT: An unrelated empty slice is not accepted as a subrange of nonempty bytes.
///
/// HOW:
/// - Pass an empty literal slice to `slice_ref` on `012345678` and expect a panic.
#[test]
#[should_panic]
fn slice_ref_catches_not_an_empty_subset() {
    let bytes = Bytes::from(&b"012345678"[..]);
    let slice = &b""[0..0];

    bytes.slice_ref(slice);
}

/// STATEMENT: Even an empty buffer rejects an empty referenced slice from unrelated storage.
///
/// HOW:
/// - Copy an empty slice into `Bytes`, pass a separate empty literal to `slice_ref`, and expect a panic.
#[test]
#[should_panic]
fn empty_slice_ref_catches_not_an_empty_subset() {
    let bytes = Bytes::copy_from_slice(&b""[..]);
    let slice = &b""[0..0];

    bytes.slice_ref(slice);
}

/// STATEMENT: Freezing mutable bytes preserves payloads and inlines short data.
///
/// HOW:
/// - Freeze copied `12345` and `LONG`, compare data before and after each conversion, and verify the short result is inline.
#[test]
fn bytes_vec_freeze() {
    let bytes = BytesMut::copy_from_slice(b"12345");
    assert_eq!(bytes, &b"12345"[..]);
    let b = bytes.freeze();
    assert_eq!(b, &b"12345"[..]);
    assert!(b.is_inline());

    let bytes = BytesMut::copy_from_slice(LONG);
    assert_eq!(bytes, LONG);
    let b = bytes.freeze();
    assert_eq!(b, LONG);
}

/// STATEMENT: Mutable conversions from strings and arrays preserve data and support prefix splitting.
///
/// HOW:
/// - Convert `12345`, split three bytes, and compare both directions of equality for `123` and the retained `45`.
/// - Convert `[1, 2, 3]` and compare the corresponding byte sequence.
#[test]
fn bytes_vec() {
    let mut bytes = BytesMut::from("12345");
    assert_eq!(bytes, "12345");
    assert_eq!("12345", bytes);
    let b: Bytes = bytes.split_to(3);
    assert_eq!(b, "123");
    assert_eq!("123", b);
    assert_eq!(bytes, "45");

    let data: [u8; 3] = [1, 2, 3];
    let bytes = BytesMut::from(data);
    assert_eq!(bytes, b"\x01\x02\x03");
}

/// STATEMENT: Allocating at the 32-bit capacity limit is rejected when it exceeds the supported maximum.
///
/// HOW:
/// - On a 64-bit target, request `u32::MAX` capacity and expect the `exceeds maximum` panic.
#[cfg(target_pointer_width = "64")]
#[test]
#[should_panic(expected = "exceeds maximum")]
fn with_capacity_over_u32() {
    let _ = BytesMut::with_capacity(u32::MAX as usize);
}

/// STATEMENT: Reserving beyond supported allocation capacity panics instead of truncating the request.
///
/// HOW:
/// - On a 64-bit target, reserve `u32::MAX` additional bytes after `hello` and expect the maximum-capacity panic.
#[cfg(target_pointer_width = "64")]
#[test]
#[should_panic(expected = "exceeds maximum")]
fn reserve_over_u32() {
    let mut buf = BytesMut::copy_from_slice(b"hello");
    buf.reserve(u32::MAX as usize);
}

/// STATEMENT: Reservation detects arithmetic overflow when adding requested space to live data.
///
/// HOW:
/// - Reserve `usize::MAX` additional bytes after `hello` and expect the buffer-capacity overflow panic.
#[test]
#[should_panic(expected = "buffer capacity overflow")]
fn reserve_overflows_usize() {
    let mut buf = BytesMut::copy_from_slice(b"hello");
    buf.reserve(usize::MAX);
}

/// Fills the buffer until less than the low threshold of its page size remains.
fn fill_low(buf: &mut BytesMut) {
    let low = buf.page_size().low();
    let remaining = buf.capacity() - buf.len();
    if remaining >= low {
        buf.extend_from_slice(&vec![1; remaining - low + 1]);
    }
}

/// STATEMENT: `reserve_more` grows low-space pages through size classes and eventually falls back to ordinary storage.
///
/// HOW:
/// - Check ample spare space is unchanged, then fill below each low threshold and verify successive classes, capacities, lengths, and payloads.
/// - Grow beyond `Size256` by 64 KiB and grow a shared `Size8` page, checking both the new tail and retained head data.
#[test]
fn reserve_more_pages() {
    // the remaining capacity is above the low threshold
    let mut buf = BytesMut::with_page_size(BytePageSize::Size4);
    buf.extend_from_slice(LONG);
    buf.reserve_more();
    assert_eq!(buf.page_size(), BytePageSize::Size4);
    assert_eq!(&buf[..], LONG);

    // every page size moves to the next one
    let mut size = BytePageSize::Size4;
    while size != BytePageSize::Size256 {
        fill_low(&mut buf);
        let len = buf.len();
        size = size.next();
        buf.reserve_more();
        assert_eq!(buf.page_size(), size);
        assert_eq!(buf.capacity(), size.capacity());
        assert_eq!(buf.len(), len);
        assert_eq!(&buf[..LONG.len()], LONG);
    }

    // above the largest page size, a regular buffer grows by 64 KiB
    fill_low(&mut buf);
    buf.reserve_more();
    assert_eq!(buf.page_size(), BytePageSize::Unset);
    assert_eq!(buf.capacity(), BytePageSize::Size256.capacity() + 64 * 1024);
    assert_eq!(&buf[..LONG.len()], LONG);

    // a shared page moves too, split off data stays valid
    let mut buf = BytesMut::with_page_size(BytePageSize::Size8);
    buf.extend_from_slice(LONG);
    buf.extend_from_slice(SHORT);
    let head = buf.split_to(LONG.len());
    fill_low(&mut buf);
    buf.reserve_more();
    assert_eq!(buf.page_size(), BytePageSize::Size16);
    assert_eq!(buf.capacity(), BytePageSize::Size16.capacity());
    assert_eq!(&buf[..SHORT.len()], SHORT);
    assert_eq!(&head[..], LONG);
}

/// STATEMENT: `reserve_more` reuses a page's size for small live data and grows the class for larger live data.
///
/// HOW:
/// - Leave 100 bytes after consuming unique and shared `Size8` pages, reserve more, and check class, capacity, data, and retained head bytes.
/// - Leave more than the half-capacity threshold and verify growth to `Size16` without changing length.
#[test]
fn reserve_more_reuses_page() {
    // a unique page with consumed data is compacted in place
    let mut buf = BytesMut::with_page_size(BytePageSize::Size8);
    fill_low(&mut buf);
    buf.advance(buf.len() - 100);
    let ptr = buf.as_ptr();
    buf.reserve_more();
    assert_eq!(buf.page_size(), BytePageSize::Size8);
    assert_eq!(buf.capacity(), BytePageSize::Size8.capacity());
    assert_eq!(&buf[..], &[1; 100][..]);
    assert_ne!(buf.as_ptr(), ptr);

    // a shared page with little data moves to a page of the same size
    let mut buf = BytesMut::with_page_size(BytePageSize::Size8);
    fill_low(&mut buf);
    let head = buf.split_to(buf.len() - 100);
    buf.reserve_more();
    assert_eq!(buf.page_size(), BytePageSize::Size8);
    assert_eq!(buf.capacity(), BytePageSize::Size8.capacity());
    assert_eq!(&buf[..], &[1; 100][..]);
    assert!(head.iter().all(|b| *b == 1));

    // more than half a page of data grows the page
    let mut buf = BytesMut::with_page_size(BytePageSize::Size8);
    fill_low(&mut buf);
    let len = BytePageSize::Size8.capacity() - BytePageSize::Size8.half_capacity() + 1;
    buf.advance(buf.len() - len);
    buf.reserve_more();
    assert_eq!(buf.page_size(), BytePageSize::Size16);
    assert_eq!(buf.len(), len);
}

/// STATEMENT: Ordinary-buffer `reserve_more` uses bounded growth and reclaims consumed unique storage when possible.
///
/// HOW:
/// - Check empty, small, and larger buffers grow by the minimum, doubling, or a 64-KiB step while preserving payloads.
/// - Consume most of unique buffers and check compaction preserves capacity, then reserve shared storage and verify both split views remain valid.
#[test]
fn reserve_more_unset() {
    let mut buf = BytesMut::copy_from_slice(b"");
    assert_eq!(buf.capacity(), 0);
    buf.reserve_more();
    assert_eq!(buf.capacity(), MIN_CAPACITY);

    let mut buf = BytesMut::copy_from_slice(LONG);
    buf.reserve_more();
    assert_eq!(buf.capacity(), LONG.len() + MIN_CAPACITY);
    assert_eq!(&buf[..], LONG);

    let mut buf = BytesMut::with_capacity(1000);
    buf.extend_from_slice(LONG);
    buf.reserve_more();
    assert_eq!(buf.capacity(), 2000);
    assert_eq!(buf.page_size(), BytePageSize::Unset);
    assert_eq!(&buf[..], LONG);

    // the step is limited to 64 KiB
    let mut buf = BytesMut::with_capacity(100_000);
    buf.extend_from_slice(LONG);
    buf.reserve_more();
    assert_eq!(buf.capacity(), 100_000);
    fill_low(&mut buf);
    buf.reserve_more();
    assert_eq!(buf.capacity(), 100_000 + 64 * 1024);
    assert_eq!(&buf[..LONG.len()], LONG);

    // a unique buffer with consumed data is compacted in place
    let mut buf = BytesMut::with_capacity(100_000);
    buf.extend_from_slice(&vec![1; 100_000]);
    buf.advance(99_000);
    buf.reserve_more();
    assert_eq!(buf.capacity(), 100_000);
    assert_eq!(&buf[..], &[1; 1000][..]);

    // a unique buffer is reclaimed when its allocation is large enough
    let mut buf = BytesMut::with_capacity(1000);
    buf.extend_from_slice(&[1; 1000]);
    buf.advance(900);
    let ptr = buf.as_ptr();
    buf.reserve_more();
    assert_eq!(buf.capacity(), 1000);
    assert_eq!(&buf[..], &[1; 100][..]);
    assert_ne!(buf.as_ptr(), ptr);

    // a shared buffer is copied, split off data stays valid
    let mut buf = BytesMut::with_capacity(1000);
    buf.extend_from_slice(LONG);
    buf.extend_from_slice(SHORT);
    let head = buf.split_to(LONG.len());
    let cap = buf.capacity();
    buf.reserve_more();
    assert_eq!(buf.capacity(), cap + MIN_CAPACITY.max(cap));
    assert_eq!(&buf[..], SHORT);
    assert_eq!(&head[..], LONG);
}

/// STATEMENT: Setting visible length beyond the 32-bit range cannot silently truncate to fit a small allocation.
///
/// HOW:
/// - On a 64-bit target, set a capacity-64 buffer's length to `(1 << 32) + 5` and expect a panic.
#[cfg(target_pointer_width = "64")]
#[test]
#[should_panic]
fn set_len_over_u32() {
    let mut buf = BytesMut::with_capacity(64);
    // SAFETY: The implementation checks capacity and panics before exposing the oversized length.
    unsafe { buf.set_len((1 << 32) + 5) };
}

fn assert_advance_panics(name: &str, f: impl FnOnce()) {
    let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
    assert!(res.is_err(), "{name}: advance_to past len must panic");
}

/// STATEMENT: Advancement and splitting enforce visible bounds across mutable, vector, inline, static, and page storage.
///
/// HOW:
/// - Advance mutable and vector-backed immutable buffers exactly to their ends and verify emptiness.
/// - Catch overrun panics for those buffers, inline and static bytes, immutable splitting, and a storage-backed `BytePage`.
#[test]
fn advance_to_past_len_panics() {
    let long = vec![b'x'; 100];

    let mut buf = BytesMut::with_capacity(64);
    buf.extend_from_slice(b"hello");
    buf.advance_to(5);
    assert!(buf.is_empty());
    assert_advance_panics("BytesMut", || {
        let mut buf = BytesMut::with_capacity(64);
        buf.extend_from_slice(b"hello");
        buf.advance_to(6);
    });

    let mut b = Bytes::from(long.clone());
    b.advance_to(100);
    assert!(b.is_empty());
    assert_advance_panics("Bytes vec", || {
        let mut b = Bytes::from(long.clone());
        b.truncate(50);
        b.advance_to(51);
    });
    assert_advance_panics("Bytes inline", || {
        let mut b = Bytes::copy_from_slice(b"abc");
        assert!(b.is_inline());
        b.advance_to(4);
    });
    assert_advance_panics("Bytes static", || {
        Bytes::from_static(b"abc").advance_to(4);
    });
    assert_advance_panics("Bytes split_to", || {
        let _ = Bytes::from(long.clone()).split_to(101);
    });
    assert_advance_panics("BytePage", || {
        let mut buf = BytesMut::with_capacity(64);
        buf.extend_from_slice(b"hello");
        BytePage::from(buf).advance_to(6);
    });
}

/// STATEMENT: Truncating and trimming a split immutable view uses its own length rather than its mutable sibling's capacity.
///
/// HOW:
/// - Split 900 bytes from a patterned 1,000-byte buffer and check the tail and allocation capacities.
/// - Truncate the head to 800, trim it and its clone, and compare both prefixes and the untouched mutable tail.
#[test]
fn split_to_view_truncate_and_trimdown() {
    let data: Vec<u8> = (0..1000u32).map(|i| i as u8).collect();
    let mut buf = BytesMut::with_capacity(1000);
    buf.extend_from_slice(&data);

    // the `BytesMut` view capacity is smaller than the `Bytes` view length
    let mut b = buf.split_to(900);
    assert_eq!(buf.capacity(), 100);
    assert_eq!(b.info().capacity, 1000 + ntex_bytes::METADATA_SIZE);

    b.truncate(800);
    assert_eq!(b, &data[..800]);

    let mut b2 = b.clone();
    b2.trimdown();
    assert_eq!(b2, &data[..800]);
    b.trimdown();
    assert_eq!(b, &data[..800]);
    assert_eq!(buf, &data[900..]);
}

/// STATEMENT: Immutable-handle operations remain valid while a mutable sibling updates its disjoint view on another thread.
///
/// HOW:
/// - Split a 256-byte immutable head, then inspect, clone, truncate, and trim it on a spawned thread.
/// - Append, advance, split, reserve, and shorten the mutable tail concurrently; join and check head data, allocation capacity, and tail length.
#[test]
fn bytes_handle_concurrent_with_bytes_mut() {
    let mut buf = BytesMut::with_capacity(1024);
    buf.extend_from_slice(&[1u8; 512]);
    let b = buf.split_to(256);

    let t = std::thread::spawn(move || {
        let mut b = b;
        let info = b.info();
        let b2 = b.clone();
        b.truncate(200);
        b.trimdown();
        drop(b2);
        (info, b)
    });
    buf.extend_from_slice(&[2u8; 16]);
    buf.advance_to(8);
    let _ = buf.split_to(32);
    buf.reserve(64);
    // SAFETY: The buffer is nonempty and shortening it retains only initialized bytes.
    unsafe { buf.set_len(buf.len() - 1) };

    let (info, b) = t.join().unwrap();
    assert_eq!(info.capacity, 1024 + ntex_bytes::METADATA_SIZE);
    assert_eq!(b, &[1u8; 200][..]);
    assert_eq!(buf.len(), 256 + 16 - 8 - 32 - 1);
}

/// STATEMENT: Large advancement and split counts are bounds-checked without truncation to 32 bits.
///
/// HOW:
/// - On 64-bit targets, catch panics for `(1 << 32) + 1` advancement or splitting of short mutable buffers and storage- or vector-backed pages.
#[test]
#[cfg(target_pointer_width = "64")]
fn advance_to_does_not_truncate_count() {
    const CNT: usize = (1 << 32) + 1;

    assert_advance_panics("BytesMut", || {
        let mut buf = BytesMut::with_capacity(64);
        buf.extend_from_slice(b"hello");
        buf.advance_to(CNT);
    });
    assert_advance_panics("BytesMut split_to", || {
        let mut buf = BytesMut::with_capacity(64);
        buf.extend_from_slice(b"hello");
        let _ = buf.split_to(CNT);
    });
    assert_advance_panics("BytePage", || {
        let mut buf = BytesMut::with_capacity(64);
        buf.extend_from_slice(b"hello");
        BytePage::from(buf).advance_to(CNT);
    });
    assert_advance_panics("BytePage vec", || {
        BytePage::from(b"hello".to_vec()).advance_to(CNT);
    });
}

fn storage_page(data: &[u8]) -> BytePage {
    let mut buf = BytesMut::with_capacity(128);
    buf.extend_from_slice(data);
    let page = BytePage::from(buf);
    assert_eq!(page.info(), ntex_bytes::info::PageKind::Storage);
    page
}

/// STATEMENT: Page clones have independent views and mutable conversions isolate shared data while reusing unique allocations.
///
/// HOW:
/// - Advance a cloned storage-backed page and check the clone retains all bytes.
/// - Convert shared clones to mutable buffers, modify and append independently, then verify all payloads and unique-page pointer reuse.
#[test]
fn page_clone_is_independent() {
    let data = [b'a'; 64];

    let mut p = storage_page(&data);
    let c = p.clone();
    p.advance_to(6);
    assert_eq!(c, &data[..]);
    assert_eq!(p, &data[6..]);

    let p = storage_page(&data);
    let c = p.clone();
    let c2 = c.clone();
    let mut m = BytesMut::from(p);
    m[0] = b'X';
    m.extend_from_slice(b"!!");
    let mut m2 = BytesMut::from(c2);
    m2.extend_from_slice(b"??");
    assert_eq!(c, &data[..]);
    assert_eq!(&m[..], [&b"X"[..], &data[1..], b"!!"].concat());
    assert_eq!(&m2[..], [&data[..], b"??"].concat());

    // a unique page is converted without a copy
    let p = storage_page(&data);
    let ptr = p.as_ref().as_ptr();
    drop(p.clone());
    assert_eq!(BytesMut::from(p).as_ptr(), ptr);
}

/// STATEMENT: Cloned page views can advance independently on different threads.
///
/// HOW:
/// - Clone a 64-byte storage page, advance the clone by one on a thread and the source by two, then join and compare their suffixes.
#[test]
fn page_clone_across_threads() {
    let data = [b'a'; 64];
    let mut p = storage_page(&data);
    let c = p.clone();

    let t = std::thread::spawn(move || {
        let mut c = c;
        c.advance_to(1);
        c
    });
    p.advance_to(2);
    let c = t.join().unwrap();
    assert_eq!(c, &data[1..]);
    assert_eq!(p, &data[2..]);
}

/// STATEMENT: Native `BufMut::put` grows mutable storage for sources larger than current spare capacity.
///
/// HOW:
/// - Put 5,000 bytes into an empty buffer, then put the same payload as `Bytes` after `ab` in a capacity-16 buffer.
/// - Compare the complete first payload and both ranges of the second buffer.
#[test]
fn buf_mut_put_grows() {
    let data = vec![7u8; 5000];
    let mut buf = BytesMut::new();
    BufMut::put(&mut buf, &data[..]);
    assert_eq!(&buf[..], &data[..]);

    // source larger than the spare capacity
    let src = Bytes::from(data.clone());
    let mut buf = BytesMut::with_capacity(16);
    BufMut::put(&mut buf, &b"ab"[..]);
    BufMut::put(&mut buf, src);
    assert_eq!(&buf[..2], b"ab");
    assert_eq!(&buf[2..], &data[..]);
}

/// STATEMENT: Mutable-reference and boxed `BufMut` forwarding preserve growable write behavior.
///
/// HOW:
/// - Through a generic writer, append a 5,000-byte slice twice and two single bytes to `&mut BytesMut` and `Box<BytesMut>`.
/// - Verify both resulting lengths equal twice the payload length plus two.
#[test]
fn buf_mut_forwarding_grow() {
    let data = vec![5u8; 5000];

    // &mut BytesMut and Box<BytesMut> forward to the growable impl
    fn fill<B: BufMut>(mut b: B, data: &[u8]) {
        b.put_slice(data);
        b.put(data);
        b.put_u8(1);
        b.put_i8(2);
    }
    let mut buf = BytesMut::new();
    fill(&mut buf, &data);
    assert_eq!(buf.len(), 2 * data.len() + 2);
    let mut buf = Box::new(BytesMut::new());
    fill(&mut buf, &data);
    assert_eq!(buf.len(), 2 * data.len() + 2);
}