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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Consolidated DST tests (Arc/Rc, Box, and panic-safety paths).

#![cfg(feature = "dst")]

mod common;

// === merged from tests/dst.rs ===
mod dst {
    #![allow(clippy::clone_on_ref_ptr, reason = "tests prefer concise method-call form")]
    #![allow(clippy::std_instead_of_core, reason = "tests use std")]
    #![allow(clippy::unwrap_used, reason = "test code")]
    #![allow(clippy::multiple_unsafe_ops_per_block, reason = "tests group related unsafe ops")]
    #![allow(clippy::cast_possible_truncation, reason = "test data is small")]
    #![allow(clippy::assertions_on_result_states, reason = "tests prefer assert!")]
    #![allow(clippy::undocumented_unsafe_blocks, reason = "test code")]
    use core::sync::atomic::{AtomicUsize, Ordering};

    use multitude::Arena;

    #[expect(unused_imports, reason = "merged test module re-exports common helpers")]
    use crate::common;

    #[test]
    fn alloc_dst_rc_byte_slice() {
        let arena = Arena::new();
        let len = 5_usize;
        let layout = core::alloc::Layout::array::<u8>(len).unwrap();
        // SAFETY: layout matches [u8; 5]; metadata is len; init writes len bytes.
        let r = unsafe {
            arena.alloc_dst_rc::<[u8]>(layout, len, |fat: *mut [u8]| {
                let p = fat.cast::<u8>();
                for i in 0..len {
                    p.add(i).write((i + 100) as u8);
                }
            })
        };
        assert_eq!(r.len(), 5);
        for (i, byte) in r.iter().enumerate() {
            assert_eq!(*byte, (i + 100) as u8);
        }
    }

    #[test]
    fn try_alloc_dst_rc_succeeds() {
        let arena = Arena::new();
        let layout = core::alloc::Layout::array::<u32>(2).unwrap();
        // SAFETY: layout matches [u32; 2]; metadata is len; init writes 2 u32s.
        let r = unsafe {
            arena
                .try_alloc_dst_rc::<[u32]>(layout, 2_usize, |fat: *mut [u32]| {
                    let p = fat.cast::<u32>();
                    p.add(0).write(7);
                    p.add(1).write(8);
                })
                .unwrap()
        };
        assert_eq!(&*r, &[7, 8]);
    }

    #[test]
    fn alloc_dst_arc_byte_slice() {
        let arena = Arena::new();
        let len = 5_usize;
        let layout = core::alloc::Layout::array::<u8>(len).unwrap();
        // SAFETY: layout matches [u8; 5]; metadata is len; init writes len bytes.
        let r = unsafe {
            arena.alloc_dst_arc::<[u8]>(layout, len, |fat: *mut [u8]| {
                let p = fat.cast::<u8>();
                for i in 0..len {
                    p.add(i).write((i + 200) as u8);
                }
            })
        };
        assert_eq!(r.len(), 5);
        for (i, byte) in r.iter().enumerate() {
            assert_eq!(*byte, (i + 200) as u8);
        }
    }

    #[test]
    fn try_alloc_dst_arc_succeeds() {
        let arena = Arena::new();
        let layout = core::alloc::Layout::array::<u8>(3).unwrap();
        // SAFETY: layout matches [u8; 3]; init writes 3 bytes.
        let r = unsafe {
            arena
                .try_alloc_dst_arc::<[u8]>(layout, 3_usize, |fat: *mut [u8]| {
                    let p = fat.cast::<u8>();
                    p.add(0).write(1);
                    p.add(1).write(2);
                    p.add(2).write(3);
                })
                .unwrap()
        };
        assert_eq!(&*r, &[1, 2, 3]);
    }

    #[test]
    fn alloc_dst_arc_outlives_arena() {
        let r = {
            let arena = Arena::new();
            let layout = core::alloc::Layout::array::<u32>(4).unwrap();
            // SAFETY: layout matches [u32; 4]; init writes 4 u32s.
            unsafe {
                arena.alloc_dst_arc::<[u32]>(layout, 4_usize, |fat: *mut [u32]| {
                    let p = fat.cast::<u32>();
                    for i in 0..4 {
                        p.add(i).write(11 * (i as u32 + 1));
                    }
                })
            }
        };
        assert_eq!(&*r, &[11, 22, 33, 44]);
    }

    #[test]
    fn alloc_dst_arc_send_across_threads() {
        let arena = Arena::new();
        let layout = core::alloc::Layout::array::<u32>(3).unwrap();
        // SAFETY: layout matches [u32; 3]; init writes 3 u32s.
        let r = unsafe {
            arena.alloc_dst_arc::<[u32]>(layout, 3_usize, |fat: *mut [u32]| {
                let p = fat.cast::<u32>();
                p.add(0).write(7);
                p.add(1).write(8);
                p.add(2).write(9);
            })
        };
        let r2 = r.clone();
        let h = std::thread::spawn(move || r2.iter().sum::<u32>());
        assert_eq!(h.join().unwrap(), 24);
        assert_eq!(&*r, &[7, 8, 9]);
    }

    #[test]
    fn alloc_dst_rc_runs_drop_at_chunk_teardown() {
        static COUNT: AtomicUsize = AtomicUsize::new(0);
        struct Tracked(#[expect(dead_code, reason = "field exists only for size")] u32);
        impl Drop for Tracked {
            fn drop(&mut self) {
                let _ = COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        COUNT.store(0, Ordering::SeqCst);
        {
            let arena = Arena::new();
            let layout = core::alloc::Layout::array::<Tracked>(3).unwrap();
            // SAFETY: layout matches [Tracked; 3]; init writes 3 Tracked.
            let r = unsafe {
                arena.alloc_dst_rc::<[Tracked]>(layout, 3_usize, |fat: *mut [Tracked]| {
                    let p = fat.cast::<Tracked>();
                    p.add(0).write(Tracked(1));
                    p.add(1).write(Tracked(2));
                    p.add(2).write(Tracked(3));
                })
            };
            assert_eq!(r.len(), 3);
            assert_eq!(COUNT.load(Ordering::SeqCst), 0);
            drop(r);
        }
        assert_eq!(COUNT.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn try_alloc_dst_rc_rejects_excessive_alignment() {
        let arena: Arena = Arena::new();
        let huge_align = 128 * 1024_usize;
        let layout = core::alloc::Layout::from_size_align(huge_align, huge_align).unwrap();
        let r = unsafe {
            arena.try_alloc_dst_rc::<[u8]>(layout, 0_usize, |_| {
                unreachable!("init must not be called when allocation fails");
            })
        };
        assert!(r.is_err());
    }

    #[test]
    fn try_alloc_dst_rc_rejects_half_chunk_alignment() {
        // align = 32 KiB sits exactly at the smart-pointer alignment cap. The
        // DropEntry's pre-payload bytes would push the value to chunk offset
        // CHUNK_ALIGN (= 64 KiB), making `header_for(value_ptr)` mask to the
        // wrong chunk header. The guard must reject this layout.
        let arena: Arena = Arena::new();
        let half_chunk = 32 * 1024_usize;
        let layout = core::alloc::Layout::from_size_align(half_chunk, half_chunk).unwrap();
        let r = unsafe {
            arena.try_alloc_dst_rc::<[u8]>(layout, 0_usize, |_| {
                unreachable!("init must not be called when allocation fails");
            })
        };
        assert!(r.is_err());
    }

    #[test]
    fn try_alloc_dst_arc_rejects_half_chunk_alignment() {
        let arena: Arena = Arena::new();
        let half_chunk = 32 * 1024_usize;
        let layout = core::alloc::Layout::from_size_align(half_chunk, half_chunk).unwrap();
        let r = unsafe {
            arena.try_alloc_dst_arc::<[u8]>(layout, 0_usize, |_| {
                unreachable!("init must not be called when allocation fails");
            })
        };
        assert!(r.is_err());
    }

    #[test]
    fn try_alloc_dst_box_rejects_half_chunk_alignment() {
        let arena: Arena = Arena::new();
        let half_chunk = 32 * 1024_usize;
        let layout = core::alloc::Layout::from_size_align(half_chunk, half_chunk).unwrap();
        let r = unsafe {
            arena.try_alloc_dst_box::<[u8]>(layout, 0_usize, |_| {
                unreachable!("init must not be called when allocation fails");
            })
        };
        assert!(r.is_err());
    }
}

// === merged from tests/dst_box.rs ===
mod dst_box {
    #![allow(clippy::std_instead_of_core, reason = "tests use std")]
    #![allow(clippy::unwrap_used, reason = "test code")]
    #![allow(clippy::multiple_unsafe_ops_per_block, reason = "tests group related unsafe ops")]
    #![allow(clippy::missing_panics_doc, reason = "test code")]
    #![allow(clippy::cast_possible_truncation, reason = "test indices are small and bounded")]
    use core::sync::atomic::{AtomicUsize, Ordering};

    use multitude::Arena;

    #[expect(unused_imports, reason = "merged test module re-exports common helpers")]
    use crate::common;

    #[test]
    fn alloc_dst_box_byte_slice() {
        let arena = Arena::new();
        let len = 10_usize;
        let layout = core::alloc::Layout::array::<u8>(len).unwrap();
        // SAFETY: layout matches [u8; 10]; init writes len bytes.
        let b = unsafe {
            arena.alloc_dst_box::<[u8]>(layout, len, |fat: *mut [u8]| {
                let p = fat.cast::<u8>();
                for i in 0..len {
                    p.add(i).write(i as u8);
                }
            })
        };
        assert_eq!(b.len(), 10);
        for (i, byte) in b.iter().enumerate() {
            assert_eq!(*byte, i as u8);
        }
    }

    #[test]
    fn try_alloc_dst_box_succeeds() {
        let arena = Arena::new();
        let layout = core::alloc::Layout::array::<u32>(2).unwrap();
        // SAFETY: layout matches [u32; 2]; init fully initializes.
        let b = unsafe {
            arena
                .try_alloc_dst_box::<[u32]>(layout, 2_usize, |fat: *mut [u32]| {
                    let p = fat.cast::<u32>();
                    p.add(0).write(11);
                    p.add(1).write(22);
                })
                .unwrap()
        };
        assert_eq!(&*b, &[11, 22]);
    }

    #[test]
    fn alloc_dst_box_runs_drop_immediately() {
        static COUNT: AtomicUsize = AtomicUsize::new(0);
        struct Tracked(String);
        impl Drop for Tracked {
            fn drop(&mut self) {
                let _ = COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        COUNT.store(0, Ordering::SeqCst);
        let arena = Arena::new();
        let layout = core::alloc::Layout::array::<Tracked>(3).unwrap();
        // SAFETY: layout matches [Tracked; 3]; init writes 3 elements.
        let b = unsafe {
            arena.alloc_dst_box::<[Tracked]>(layout, 3_usize, |fat: *mut [Tracked]| {
                let p = fat.cast::<Tracked>();
                p.add(0).write(Tracked("a".to_string()));
                p.add(1).write(Tracked("b".to_string()));
                p.add(2).write(Tracked("c".to_string()));
            })
        };
        assert_eq!(b.len(), 3);
        assert_eq!(b[0].0, "a");
        assert_eq!(b[2].0, "c");

        let before = COUNT.load(Ordering::SeqCst);
        drop(b);
        assert_eq!(
            COUNT.load(Ordering::SeqCst),
            before + 3,
            "drop_in_place([T;3]) must drop each element"
        );
        drop(arena);
        assert_eq!(COUNT.load(Ordering::SeqCst), before + 3, "no extra drops at arena teardown");
    }

    #[test]
    fn alloc_slice_copy_box_basic() {
        let arena = Arena::new();
        let b = arena.alloc_slice_copy_box([1_u32, 2, 3]);
        assert_eq!(&*b, &[1, 2, 3]);

        // Folded from_coverage_extras_dst::alloc_slice_copy_box_succeeds keeps the alternate payload assertion.
        let b: multitude::Box<[u8]> = arena.alloc_slice_copy_box([10_u8, 20, 30]);
        assert_eq!(&*b, &[10, 20, 30]);
    }

    #[test]
    fn alloc_slice_copy_box_mutable() {
        let arena = Arena::new();
        let mut b = arena.alloc_slice_copy_box([10_u32, 20, 30]);
        b[1] = 200;
        assert_eq!(&*b, &[10, 200, 30]);
    }

    #[test]
    fn try_alloc_slice_copy_box_works() {
        let arena = Arena::new();
        let b = arena.try_alloc_slice_copy_box([1_u8, 2, 3]).unwrap();
        assert_eq!(&*b, &[1, 2, 3]);
    }

    #[test]
    fn alloc_slice_clone_box_basic() {
        let arena = Arena::new();
        let originals = [
            std::string::String::from("a"),
            std::string::String::from("b"),
            std::string::String::from("c"),
        ];
        let b = arena.alloc_slice_clone_box(&originals);
        assert_eq!(b.len(), 3);
        assert_eq!(b[0], "a");
        assert_eq!(b[2], "c");

        // Folded from_coverage_extras_dst::alloc_slice_clone_box_succeeds keeps the alternate input case.
        let src = [
            std::string::String::from("x"),
            std::string::String::from("y"),
            std::string::String::from("z"),
        ];
        let b: multitude::Box<[String]> = arena.alloc_slice_clone_box(src);
        assert_eq!(b.len(), 3);
        assert_eq!(b[2], "z");
    }

    #[test]
    fn try_alloc_slice_clone_box_works() {
        let arena = Arena::new();
        let b = arena.try_alloc_slice_clone_box([100_u32, 200]).unwrap();
        assert_eq!(&*b, &[100, 200]);
    }

    #[test]
    fn alloc_slice_fill_with_box_basic() {
        let arena = Arena::new();
        let b: multitude::Box<[u64]> = arena.alloc_slice_fill_with_box(5, |i| (i as u64) * 10);
        assert_eq!(&*b, &[0, 10, 20, 30, 40]);

        // Folded from_coverage_extras_dst::alloc_slice_fill_with_box_succeeds keeps the shorter fill case.
        let b: multitude::Box<[u32]> = arena.alloc_slice_fill_with_box(4, |i| (i + 1) as u32);
        assert_eq!(&*b, &[1, 2, 3, 4]);
    }

    #[test]
    fn try_alloc_slice_fill_with_box_works() {
        let arena = Arena::new();
        let b: multitude::Box<[u32]> = arena.try_alloc_slice_fill_with_box(3, |i| u32::try_from(i + 100).unwrap()).unwrap();
        assert_eq!(&*b, &[100, 101, 102]);
    }

    #[test]
    fn alloc_slice_fill_iter_box_basic() {
        let arena = Arena::new();
        let b: multitude::Box<[i32]> = arena.alloc_slice_fill_iter_box([7_i32, 8, 9]);
        assert_eq!(&*b, &[7, 8, 9]);

        // Folded from_coverage_extras_dst::alloc_slice_fill_iter_box_succeeds keeps the range-based iterator case.
        let b: multitude::Box<[u8]> = arena.alloc_slice_fill_iter_box(0_u8..5);
        assert_eq!(&*b, &[0, 1, 2, 3, 4]);
    }

    #[test]
    fn try_alloc_slice_fill_iter_box_works() {
        let arena = Arena::new();
        let b: multitude::Box<[u32]> = arena.try_alloc_slice_fill_iter_box([42_u32, 43, 44]).unwrap();
        assert_eq!(&*b, &[42, 43, 44]);
    }

    #[test]
    fn alloc_slice_fill_iter_box_empty() {
        let arena = Arena::new();
        let b: multitude::Box<[u32]> = arena.alloc_slice_fill_iter_box(core::iter::empty::<u32>());
        assert!(b.is_empty());
    }

    // Drop semantics: ArenaBox<[T]>::Drop must run T::drop on each element
    // IMMEDIATELY before the chunk reclaims.

    #[test]
    fn alloc_slice_clone_box_drops_elements_immediately() {
        static COUNT: AtomicUsize = AtomicUsize::new(0);
        #[derive(Clone)]
        struct Tracked;
        impl Drop for Tracked {
            fn drop(&mut self) {
                let _ = COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        COUNT.store(0, Ordering::SeqCst);
        let arena = Arena::new();
        let originals = [Tracked, Tracked, Tracked];
        let b = arena.alloc_slice_clone_box(&originals);
        assert_eq!(b.len(), 3);
        let count_before = COUNT.load(Ordering::SeqCst);
        drop(b);
        let count_after = COUNT.load(Ordering::SeqCst);
        assert_eq!(count_after - count_before, 3, "drop_in_place([T;3]) must drop each element");

        // The arena drop must NOT run drops again (entry was unlinked).
        drop(originals);
        drop(arena);
        // After arena drop: count includes the originals drop (3 more), but no
        // double-drop of the box's elements.
        assert_eq!(COUNT.load(Ordering::SeqCst), count_after + 3);
    }

    #[test]
    fn alloc_slice_fill_with_box_drops_elements_immediately() {
        static COUNT: AtomicUsize = AtomicUsize::new(0);
        struct Tracked;
        impl Drop for Tracked {
            fn drop(&mut self) {
                let _ = COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        COUNT.store(0, Ordering::SeqCst);
        let arena = Arena::new();
        let b: multitude::Box<[Tracked]> = arena.alloc_slice_fill_with_box(5, |_| Tracked);
        assert_eq!(b.len(), 5);
        let before = COUNT.load(Ordering::SeqCst);
        drop(b);
        assert_eq!(COUNT.load(Ordering::SeqCst), before + 5);
        drop(arena); // No double-drop.
        assert_eq!(COUNT.load(Ordering::SeqCst), before + 5);
    }

    #[test]
    fn alloc_slice_copy_box_no_drop_for_copy_types() {
        let arena = Arena::new();
        let b = arena.alloc_slice_copy_box([1_u8, 2, 3, 4, 5]);
        assert_eq!(b.len(), 5);
        drop(b);
        let b2 = arena.alloc_slice_copy_box([9_u8, 8, 7]);
        assert_eq!(&*b2, &[9, 8, 7]);
    }

    #[test]
    fn alloc_slice_fill_with_box_zero_len_works() {
        let arena = Arena::new();
        let b: multitude::Box<[u32]> = arena.alloc_slice_fill_with_box(0, |_| panic!("never called"));
        assert!(b.is_empty());
    }

    #[test]
    fn alloc_slice_fill_with_box_zst_with_drop() {
        static COUNT: AtomicUsize = AtomicUsize::new(0);
        struct ZstDrop;
        impl Drop for ZstDrop {
            fn drop(&mut self) {
                let _ = COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        COUNT.store(0, Ordering::SeqCst);
        let arena = Arena::new();
        let b: multitude::Box<[ZstDrop]> = arena.alloc_slice_fill_with_box(7, |_| ZstDrop);
        drop(b);
        assert_eq!(COUNT.load(Ordering::SeqCst), 7);
    }

    #[test]
    fn alloc_slice_fill_with_box_panic_drops_initialized_prefix() {
        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
        struct DropCounter;
        impl Drop for DropCounter {
            fn drop(&mut self) {
                let _ = DROP_COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        DROP_COUNT.store(0, Ordering::SeqCst);
        let arena = Arena::new();
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            // Panic at index 3, after producing 3 DropCounters.
            let _b: multitude::Box<[DropCounter]> = arena.alloc_slice_fill_with_box(10, |i| {
                assert!(i != 3, "intentional");
                DropCounter
            });
        }));
        assert!(result.is_err());
        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 3);
        let b: multitude::Box<[u32]> = arena.alloc_slice_fill_with_box(2, |i| u32::try_from(i).unwrap());
        assert_eq!(&*b, &[0, 1]);
    }

    #[test]
    #[should_panic(expected = "caller violated ExactSizeIterator contract")]
    fn alloc_slice_fill_iter_box_panics_on_short_iter() {
        struct Liar(usize);
        impl Iterator for Liar {
            type Item = u32;
            fn next(&mut self) -> Option<u32> {
                None
            }
        }
        impl ExactSizeIterator for Liar {
            fn len(&self) -> usize {
                self.0
            }
        }
        let arena = Arena::new();
        let _b: multitude::Box<[u32]> = arena.alloc_slice_fill_iter_box(Liar(2));
    }

    #[test]
    fn alloc_slice_box_high_alignment_drop_locates_entry_correctly() {
        static COUNT: AtomicUsize = AtomicUsize::new(0);
        #[repr(align(32))]
        struct A32(#[expect(dead_code, reason = "field present only to give the type a non-zero size")] u8);
        impl Drop for A32 {
            fn drop(&mut self) {
                let _ = COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        COUNT.store(0, Ordering::SeqCst);
        let arena = Arena::new();
        let _decoy: &mut u8 = arena.alloc(0_u8);
        let b: multitude::Box<[A32]> = arena.alloc_slice_fill_with_box(4, |_| A32(0));
        assert_eq!(b.len(), 4);
        let before = COUNT.load(Ordering::SeqCst);
        drop(b);
        assert_eq!(COUNT.load(Ordering::SeqCst), before + 4);
    }

    #[test]
    fn arena_box_slice_into_rc_basic() {
        let arena = Arena::new();
        let b = arena.alloc_slice_copy_box([1_u32, 2, 3]);
        let r = b.into_rc();
        assert_eq!(&*r, &[1, 2, 3]);
    }

    #[test]
    fn arena_box_slice_into_rc_after_mutation() {
        let arena = Arena::new();
        let mut b = arena.alloc_slice_copy_box([10_u32, 20, 30]);
        b[1] = 99;
        let r = b.into_rc();
        assert_eq!(&*r, &[10, 99, 30]);
    }

    /// Regression: previously `Box::<[T:Drop]>::into_rc()` panicked when the
    /// `Box` came from `alloc_dst_box` because that path skipped drop-entry
    /// installation. The fix routes `try_alloc_dst_box` through the
    /// with-entry helper for `T: needs_drop`, installing a `noop_drop_shim`
    /// that `Box::into_rc` retargets to `drop_shim_slice`.
    #[test]
    fn alloc_dst_box_drop_type_into_rc_runs_drop_exactly_once() {
        struct DropCounter(std::sync::Arc<AtomicUsize>);
        impl Drop for DropCounter {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::Relaxed);
            }
        }

        // Slice DST [DropCounter]
        let counter = std::sync::Arc::new(AtomicUsize::new(0));
        {
            let arena = Arena::new();
            let len = 3_usize;
            let layout = core::alloc::Layout::array::<DropCounter>(len).unwrap();
            // SAFETY: layout matches [DropCounter; 3]; init fully writes each slot.
            let b = unsafe {
                arena.alloc_dst_box::<[DropCounter]>(layout, len, |fat: *mut [DropCounter]| {
                    let p = fat.cast::<DropCounter>();
                    for i in 0..len {
                        p.add(i).write(DropCounter(std::sync::Arc::clone(&counter)));
                    }
                })
            };
            let r = b.into_rc();
            assert_eq!(r.len(), 3);
            assert_eq!(counter.load(Ordering::Relaxed), 0, "no drops while Rc is live");
            drop(r);
            drop(arena);
        }
        assert_eq!(counter.load(Ordering::Relaxed), 3, "each element dropped exactly once");
    }

    /// Regression: the sized-DST entry point through `alloc_dst_box::<T>` for
    /// `T: Drop` previously panicked on `into_rc()` for the same reason as
    /// the slice case.
    #[test]
    fn alloc_dst_box_sized_drop_type_into_rc_runs_drop_exactly_once() {
        struct DropCounter(std::sync::Arc<AtomicUsize>);
        impl Drop for DropCounter {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::Relaxed);
            }
        }

        let counter = std::sync::Arc::new(AtomicUsize::new(0));
        {
            let arena = Arena::new();
            let layout = core::alloc::Layout::new::<DropCounter>();
            // SAFETY: layout matches DropCounter; init writes one value.
            let b = unsafe {
                arena.alloc_dst_box::<DropCounter>(layout, (), |p: *mut DropCounter| {
                    p.write(DropCounter(std::sync::Arc::clone(&counter)));
                })
            };
            let r = b.into_rc();
            assert_eq!(counter.load(Ordering::Relaxed), 0);
            drop(r);
            drop(arena);
        }
        assert_eq!(counter.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn arena_box_slice_into_rc_outlives_arena() {
        let r = {
            let arena = Arena::new();
            let b = arena.alloc_slice_copy_box([7_u8, 8, 9]);
            b.into_rc()
        };
        assert_eq!(&*r, &[7, 8, 9]);
    }

    #[test]
    fn arena_box_slice_into_rc_preserves_drop_semantics() {
        static COUNT: AtomicUsize = AtomicUsize::new(0);
        struct Tracked;
        impl Drop for Tracked {
            fn drop(&mut self) {
                let _ = COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        COUNT.store(0, Ordering::SeqCst);
        let arena = Arena::new();
        let b: multitude::Box<[Tracked]> = arena.alloc_slice_fill_with_box(3, |_| Tracked);
        let r = b.into_rc();
        assert_eq!(COUNT.load(Ordering::SeqCst), 0);
        assert_eq!(r.len(), 3);
        drop(r);
        drop(arena);
        assert_eq!(COUNT.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn arena_box_slice_into_rc_clones_share_chunk() {
        let arena = Arena::new();
        let b = arena.alloc_slice_copy_box([42_u32; 5]);
        let r = b.into_rc();
        let r2 = r.clone();
        drop(r);
        assert_eq!(&*r2, &[42; 5]);
    }

    /// Regression: a slice DST with `len > u16::MAX` and `T: Drop` must be
    /// rejected at allocation time (returns `AllocError`) so that a future
    /// `Box::<[T]>::into_rc()` call cannot find itself with no drop entry
    /// to retarget. Matches the non-DST slice-alloc paths which use the
    /// same `entry_size != 0 && len > u16::MAX` guard.
    #[test]
    fn try_alloc_dst_box_rejects_drop_slice_with_overflowing_len() {
        struct DropCounter(std::sync::Arc<AtomicUsize>);
        impl Drop for DropCounter {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::Relaxed);
            }
        }

        let arena = Arena::new();
        let n: usize = (u16::MAX as usize) + 1;
        // Layout::array fits since u16::MAX+1 elements at small size are well under isize::MAX.
        let Ok(layout) = core::alloc::Layout::array::<DropCounter>(n) else {
            // Allocator wouldn't even build the layout; the test isn't meaningful.
            return;
        };

        // SAFETY: init would write all `n` elements; we never reach that point
        // because the allocation is rejected up front by the new guard.
        let result = unsafe {
            arena.try_alloc_dst_box::<[DropCounter]>(layout, n, |_fat: *mut [DropCounter]| {
                unreachable!("alloc must be rejected before init runs");
            })
        };
        assert!(result.is_err(), "DST slice with len > u16::MAX and T: Drop must be rejected");
    }
}

// === merged from tests/dst_panic_safety.rs ===
mod dst_panic_safety {
    #![allow(clippy::std_instead_of_core, reason = "tests use std")]
    #![allow(clippy::unwrap_used, reason = "test code")]
    #![allow(clippy::multiple_unsafe_ops_per_block, reason = "tests group related unsafe ops")]
    #![allow(clippy::undocumented_unsafe_blocks, reason = "test code")]
    use std::panic::{AssertUnwindSafe, catch_unwind};

    use multitude::Arena;

    #[expect(unused_imports, reason = "merged test module re-exports common helpers")]
    use crate::common;

    /// Allocate a DST through `alloc_dst_rc` whose `init` panics; then
    /// continue using the arena and force chunk evictions. Without the
    /// noop pre-write fix, the DST helper leaves an uninitialized
    /// drop-entry slot reachable via `chunk.drop_count`, and the next
    /// eviction triggers UB by replaying it.
    #[test]
    fn dst_rc_init_panic_then_evict_is_sound() {
        let arena = Arena::new();
        // Seed some real drop entries first.
        let _r1 = arena.alloc_rc(String::from("a"));
        let _r2 = arena.alloc_rc(String::from("b"));

        let layout = core::alloc::Layout::array::<u32>(4).unwrap();
        let result = catch_unwind(AssertUnwindSafe(|| {
            // SAFETY: panic before any write — the Rc is never observed.
            unsafe {
                arena.alloc_dst_rc::<[u32]>(layout, 4_usize, |_fat: *mut [u32]| {
                    panic!("planned panic in DST init");
                });
            }
        }));
        assert!(result.is_err());

        // 256 drop-typed strings still retire multiple chunks, so eviction
        // replays the same drop-list state this test cares about.
        for _ in 0..256 {
            let _ = arena.alloc_rc(String::from("xxxxxxxxxx"));
        }
        drop(arena);
    }

    #[test]
    fn dst_arc_init_panic_then_evict_is_sound() {
        let arena = Arena::new();
        let _a1 = arena.alloc_arc(String::from("a"));
        let _a2 = arena.alloc_arc(String::from("b"));

        let layout = core::alloc::Layout::array::<u32>(4).unwrap();
        let result = catch_unwind(AssertUnwindSafe(|| {
            // SAFETY: panic before any write — the Arc is never observed.
            unsafe {
                arena.alloc_dst_arc::<[u32]>(layout, 4_usize, |_fat: *mut [u32]| {
                    panic!("planned panic in DST init");
                });
            }
        }));
        assert!(result.is_err());

        // 256 drop-typed strings still retire multiple chunks, so eviction
        // replays the same drop-list state this test cares about.
        for _ in 0..256 {
            let _ = arena.alloc_arc(String::from("xxxxxxxxxx"));
        }
        drop(arena);
    }
}

// === relocated from coverage_extras.rs (dst-gated tests) ===
mod from_coverage_extras_dst {
    #![allow(clippy::items_after_statements, reason = "relocated tests put inner types near use")]
    #![allow(clippy::clone_on_ref_ptr, reason = "relocated tests use .clone() on Arc/Rc")]
    #![allow(dead_code, reason = "relocated helpers retain fields for layout")]
    #![allow(
        unfulfilled_lint_expectations,
        reason = "relocated #[expect] may be fulfilled at file or feature level"
    )]
    #![allow(
        clippy::undocumented_unsafe_blocks,
        reason = "relocated test bodies preserve original safety reasoning"
    )]
    #![allow(clippy::multiple_unsafe_ops_per_block, reason = "relocated tests group related unsafe ops")]
    #![allow(clippy::cast_possible_truncation, reason = "relocated tests use bounded values")]
    #![allow(clippy::cast_sign_loss, reason = "relocated tests use non-negative values")]
    #![allow(clippy::empty_drop, reason = "relocated tests use empty Drop impls to mark dropability")]
    #![allow(clippy::assertions_on_result_states, reason = "relocated tests deliberately assert error returns")]
    #![allow(clippy::empty_line_after_doc_comments, reason = "relocated test doc-comments")]
    use core::sync::atomic::{AtomicUsize, Ordering};
    use std::panic::catch_unwind;

    use crate::common::FailingAllocator as _FA;
    fn fail_arena() -> Arena<_FA> {
        Arena::new_in(_FA::new(0))
    }
    fn expect_panic<F: FnOnce() + std::panic::UnwindSafe>(f: F) {
        let r = catch_unwind(f);
        assert!(r.is_err(), "expected panic");
    }

    use std::panic::AssertUnwindSafe;

    use multitude::{Arena, ArenaBuilder, Box};
    #[expect(dead_code, reason = "helper used by some relocated tests")]
    struct OneByteDrop(u8);
    impl Drop for OneByteDrop {
        fn drop(&mut self) {}
    }
    #[expect(unused_imports, reason = "relocated tests may reference common helpers")]
    use crate::common::{self, FailingAllocator, SendFailingAllocator};

    #[test]
    fn alloc_box_oversized_drop_type_uses_has_drop_layout() {
        // Same path as above, but via the box family (which also routes
        // through `oversized_layout(_, true)` for Drop-needing types).
        static DROPPED: AtomicUsize = AtomicUsize::new(0);
        struct BigDrop {
            _bytes: [u8; 4096],
        }
        impl Drop for BigDrop {
            fn drop(&mut self) {
                let _ = DROPPED.fetch_add(1, Ordering::SeqCst);
            }
        }
        DROPPED.store(0, Ordering::SeqCst);

        let arena: Arena = Arena::builder().max_normal_alloc(4 * 1024).build();
        {
            let _b: Box<BigDrop> = arena.alloc_box(BigDrop { _bytes: [0; 4096] });
        }
        assert_eq!(DROPPED.load(Ordering::SeqCst), 1);
    }

    #[test]
    #[should_panic(expected = "multitude: allocator returned AllocError")]
    fn alloc_slice_copy_box_panics_on_failing_allocator() {
        let arena: Arena<FailingAllocator> = Arena::new_in(FailingAllocator::new(0));
        let _ = arena.alloc_slice_copy_box([0_u8; 4]);
    }

    #[test]
    #[should_panic(expected = "multitude: allocator returned AllocError")]
    fn alloc_slice_clone_box_panics_on_failing_allocator() {
        let arena: Arena<FailingAllocator> = Arena::new_in(FailingAllocator::new(0));
        let _ = arena.alloc_slice_clone_box([1_u32, 2]);
    }

    #[test]
    #[should_panic(expected = "multitude: allocator returned AllocError")]
    fn alloc_slice_fill_with_box_panics_on_failing_allocator() {
        let arena: Arena<FailingAllocator> = Arena::new_in(FailingAllocator::new(0));
        let _ = arena.alloc_slice_fill_with_box::<u32, _>(4, |i| i as u32);
    }

    #[test]
    #[should_panic(expected = "multitude: allocator returned AllocError")]
    fn alloc_slice_fill_iter_box_panics_on_failing_allocator() {
        let arena: Arena<FailingAllocator> = Arena::new_in(FailingAllocator::new(0));
        let _ = arena.alloc_slice_fill_iter_box([1_u32, 2, 3]);
    }

    #[test]
    fn arena_box_slice_from_into_arena_rc_slice() {
        let arena: Arena = Arena::new();
        let b: Box<[u32]> = arena.alloc_slice_fill_with_box(3, |i| i as u32 + 10);
        let r: multitude::Rc<[u32]> = b.into();
        assert_eq!(&*r, &[10, 11, 12][..]);
    }

    #[test]
    fn panic_alloc_uninit_slice_box() {
        expect_panic(|| {
            let a = fail_arena();
            let _ = a.alloc_uninit_slice_box::<u32>(4);
        });
    }

    #[test]
    fn panic_alloc_zeroed_slice_box() {
        expect_panic(|| {
            let a = fail_arena();
            let _ = a.alloc_zeroed_slice_box::<u32>(4);
        });
    }

    #[test]
    fn try_alloc_uninit_slice_box_err() {
        let a = fail_arena();
        a.try_alloc_uninit_slice_box::<u32>(4).unwrap_err();
    }

    #[test]
    fn try_alloc_zeroed_slice_box_err() {
        let a = fail_arena();
        a.try_alloc_zeroed_slice_box::<u32>(4).unwrap_err();
    }

    #[test]
    fn dst_reserve_rejects_overaligned() {
        // Line 1946: try_reserve_dst_with_entry rejects alignment >= CHUNK_ALIGN.
        let arena = Arena::new();
        let layout = core::alloc::Layout::from_size_align(8, 131_072).unwrap();
        let result = unsafe {
            arena.try_alloc_dst_rc::<[u8]>(layout, 8_usize, |fat: *mut [u8]| {
                let p = fat.cast::<u8>();
                for i in 0..8 {
                    p.add(i).write(i as u8);
                }
            })
        };
        result.unwrap_err();
    }

    #[test]
    fn dst_init_panic_guard_releases_refcount() {
        // Lines 2145-2149: InitPanicGuard drops and releases chunk refcount on panic.
        let arena = Arena::new();
        let layout = core::alloc::Layout::array::<u8>(4).unwrap();
        let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
            unsafe {
                arena.alloc_dst_rc::<[u8]>(layout, 4_usize, |_fat: *mut [u8]| {
                    panic!("deliberate panic in DST init");
                })
            };
        }));
        assert!(result.is_err());
        // Arena should still be usable after the panic.
        let _v = arena.alloc_rc(42_u32);
    }

    #[test]
    #[expect(clippy::too_many_lines, reason = "exhaustive alignment coverage requires many similar blocks")]
    #[expect(clippy::empty_drop, reason = "Drop impls needed to make needs_drop::<T>() true")]
    fn dst_drop_shim_dispatch_various_alignments() {
        // Lines 3894-3908: dst_drop_shim_for dispatches on alignment.
        // Exercise DST allocations with various alignments to cover the match arms.
        let arena = Arena::new();

        // align=1 (trailing_zeros=0) — already covered by default [u8] tests
        // align=2 (trailing_zeros=1)
        {
            let layout = core::alloc::Layout::from_size_align(4, 2).unwrap();
            let r = unsafe {
                arena.alloc_dst_rc::<[u16]>(layout, 2_usize, |fat: *mut [u16]| {
                    let p = fat.cast::<u16>();
                    p.add(0).write(10);
                    p.add(1).write(20);
                })
            };
            assert_eq!(&*r, &[10_u16, 20]);
        }
        // align=4 (trailing_zeros=2)
        {
            let layout = core::alloc::Layout::from_size_align(8, 4).unwrap();
            let r = unsafe {
                arena.alloc_dst_rc::<[u32]>(layout, 2_usize, |fat: *mut [u32]| {
                    let p = fat.cast::<u32>();
                    p.add(0).write(100);
                    p.add(1).write(200);
                })
            };
            assert_eq!(&*r, &[100_u32, 200]);
        }
        // align=8 (trailing_zeros=3)
        {
            let layout = core::alloc::Layout::from_size_align(16, 8).unwrap();
            let r = unsafe {
                arena.alloc_dst_rc::<[u64]>(layout, 2_usize, |fat: *mut [u64]| {
                    let p = fat.cast::<u64>();
                    p.add(0).write(1000);
                    p.add(1).write(2000);
                })
            };
            assert_eq!(&*r, &[1000_u64, 2000]);
        }
        // align=16 (trailing_zeros=4)
        {
            #[repr(align(16))]
            #[derive(Debug, PartialEq)]
            struct A16(u64, u64);
            impl Drop for A16 {
                fn drop(&mut self) {}
            }
            let layout = core::alloc::Layout::from_size_align(32, 16).unwrap();
            let r = unsafe {
                arena.alloc_dst_rc::<[A16]>(layout, 2_usize, |fat: *mut [A16]| {
                    let p = fat.cast::<A16>();
                    p.add(0).write(A16(1, 2));
                    p.add(1).write(A16(3, 4));
                })
            };
            assert_eq!(r[0], A16(1, 2));
        }
        // align=32 (trailing_zeros=5)
        {
            #[repr(align(32))]
            #[derive(Debug, PartialEq)]
            struct A32(u64);
            impl Drop for A32 {
                fn drop(&mut self) {}
            }
            let layout = core::alloc::Layout::from_size_align(64, 32).unwrap();
            let r = unsafe {
                arena.alloc_dst_rc::<[A32]>(layout, 2_usize, |fat: *mut [A32]| {
                    let p = fat.cast::<A32>();
                    p.add(0).write(A32(11));
                    p.add(1).write(A32(22));
                })
            };
            assert_eq!(r[0], A32(11));
        }
        // align=64 (trailing_zeros=6)
        {
            #[repr(align(64))]
            #[derive(Debug, PartialEq)]
            struct A64(u64);
            impl Drop for A64 {
                fn drop(&mut self) {}
            }
            let layout = core::alloc::Layout::from_size_align(128, 64).unwrap();
            let r = unsafe {
                arena.alloc_dst_rc::<[A64]>(layout, 2_usize, |fat: *mut [A64]| {
                    let p = fat.cast::<A64>();
                    p.add(0).write(A64(111));
                    p.add(1).write(A64(222));
                })
            };
            assert_eq!(r[0], A64(111));
        }
        // align=128 (trailing_zeros=7)
        {
            #[repr(align(128))]
            #[derive(Debug, PartialEq)]
            struct A128(u64);
            impl Drop for A128 {
                fn drop(&mut self) {}
            }
            let layout = core::alloc::Layout::from_size_align(256, 128).unwrap();
            let r = unsafe {
                arena.alloc_dst_rc::<[A128]>(layout, 2_usize, |fat: *mut [A128]| {
                    let p = fat.cast::<A128>();
                    p.add(0).write(A128(7));
                    p.add(1).write(A128(8));
                })
            };
            assert_eq!(r[0], A128(7));
        }
        // align=256..32768 (trailing_zeros 8..15)
        macro_rules! test_align {
            ($name:ident, $align:literal) => {{
                #[repr(align($align))]
                #[derive(Debug, PartialEq)]
                struct Aligned(u64);
                impl Drop for Aligned {
                    fn drop(&mut self) {}
                }
                let layout = core::alloc::Layout::from_size_align($align * 2, $align).unwrap();
                let r = unsafe {
                    arena.alloc_dst_rc::<[Aligned]>(layout, 2_usize, |fat: *mut [Aligned]| {
                        let p = fat.cast::<Aligned>();
                        p.add(0).write(Aligned(1));
                        p.add(1).write(Aligned(2));
                    })
                };
                assert_eq!(r[0], Aligned(1));
            }};
        }
        test_align!(a256, 256);
        test_align!(a512, 512);
        test_align!(a1024, 1024);
        test_align!(a2048, 2048);
        test_align!(a4096, 4096);
        test_align!(a8192, 8192);
        test_align!(a16384, 16384);
        // NOTE: align=32768 (trailing_zeros=15) is not testable here because
        // has_drop + align=32768 places the value at offset == CHUNK_ALIGN,
        // which breaks the address-mask header lookup used by Rc::drop.
        // The match arm `15 =>` is marked #[coverage(off)] in the source.
    }

    #[test]
    fn try_alloc_dst_arc_accepts_sized_metadata() {
        let arena = Arena::new();
        let layout = core::alloc::Layout::new::<u32>();
        // SAFETY: init writes a valid `u32` through the supplied pointer.
        let result = unsafe { arena.try_alloc_dst_arc::<u32>(layout, (), |p| p.write(42_u32)) };
        let arc = result.expect("sized DST allocation through try_alloc_dst_arc should succeed");
        assert_eq!(*arc, 42);
    }

    #[test]
    fn try_alloc_dst_rc_accepts_sized_metadata() {
        let arena = Arena::new();
        let layout = core::alloc::Layout::new::<u32>();
        // SAFETY: init writes a valid `u32` through the supplied pointer.
        let result = unsafe { arena.try_alloc_dst_rc::<u32>(layout, (), |p| p.write(7_u32)) };
        let rc = result.expect("sized DST allocation through try_alloc_dst_rc should succeed");
        assert_eq!(*rc, 7);
    }

    // ---- arena.rs: refill failure paths inside DST reservation loops. ----
    //
    // These hit the `refill_local(...)?` / `refill_shared(...)?` Err arms in
    // `allocate_shared_layout` (3112), `try_reserve_dst_local_with_entry` (3227)
    // and `try_reserve_dst_shared_with_entry` (3311).
    #[test]
    fn try_alloc_dst_arc_refill_failure_propagates() {
        // Small chunk + failing allocator: first chunk acquire succeeds, the
        // refill needed for a second allocation that doesn't fit fails.
        let alloc = common::SendFailingAllocator::new(1);
        let arena = ArenaBuilder::new_in(alloc).max_normal_alloc(4096).try_build().unwrap();
        let layout = core::alloc::Layout::array::<u8>(2048).unwrap();
        let mut errs = 0;
        for _ in 0..16 {
            // SAFETY: init only invoked if allocation succeeds.
            let r = unsafe { arena.try_alloc_dst_arc::<[u8]>(layout, 2048, |_| {}) };
            if r.is_err() {
                errs += 1;
            }
        }
        assert!(errs >= 1, "expected at least one refill failure");
    }

    #[test]
    fn try_alloc_dst_rc_refill_failure_propagates() {
        let alloc = common::FailingAllocator::new(1);
        let arena = ArenaBuilder::new_in(alloc).max_normal_alloc(4096).try_build().unwrap();
        let layout = core::alloc::Layout::array::<u8>(2048).unwrap();
        let mut errs = 0;
        for _ in 0..16 {
            // SAFETY: init only invoked if allocation succeeds.
            let r = unsafe { arena.try_alloc_dst_rc::<[u8]>(layout, 2048, |_| {}) };
            if r.is_err() {
                errs += 1;
            }
        }
        assert!(errs >= 1, "expected at least one refill failure");
    }

    // Drop-needing DST path: refill failure inside `try_reserve_dst_local_with_entry`.
    #[test]
    fn try_alloc_dst_rc_drop_refill_failure_propagates() {
        let alloc = common::FailingAllocator::new(1);
        let arena = ArenaBuilder::new_in(alloc).max_normal_alloc(4096).try_build().unwrap();
        let layout = core::alloc::Layout::array::<String>(64).unwrap();
        let mut errs = 0;
        for _ in 0..16 {
            // SAFETY: init only invoked if allocation succeeds; here we never reach
            // it on the runs that fail, and on the ones that succeed we initialize
            // each element via the fat pointer.
            let r = unsafe {
                arena.try_alloc_dst_rc::<[String]>(layout, 64, |p| {
                    for i in 0..64 {
                        core::ptr::write(p.cast::<String>().add(i), String::new());
                    }
                })
            };
            if r.is_err() {
                errs += 1;
            }
        }
        assert!(errs >= 1, "expected at least one refill failure");
    }

    // Drop-needing DST shared path: refill failure inside `try_reserve_dst_shared_with_entry`.
    #[test]
    fn try_alloc_dst_arc_drop_refill_failure_propagates() {
        let alloc = common::SendFailingAllocator::new(1);
        let arena = ArenaBuilder::new_in(alloc).max_normal_alloc(4096).try_build().unwrap();
        // String isn't Send via Arc, but `Vec<u8>` is.
        let layout = core::alloc::Layout::array::<Vec<u8>>(64).unwrap();
        let mut errs = 0;
        for _ in 0..16 {
            // SAFETY: init only invoked if allocation succeeds.
            let r = unsafe {
                arena.try_alloc_dst_arc::<[Vec<u8>]>(layout, 64, |p| {
                    for i in 0..64 {
                        core::ptr::write(p.cast::<Vec<u8>>().add(i), Vec::new());
                    }
                })
            };
            if r.is_err() {
                errs += 1;
            }
        }
        assert!(errs >= 1, "expected at least one refill failure");
    }
}

// === relocated from mutants_extras.rs (dst-gated tests) ===
mod from_mutants_extras_dst {
    #![allow(clippy::items_after_statements, reason = "relocated tests put inner types near use")]
    #![allow(clippy::clone_on_ref_ptr, reason = "relocated tests use .clone() on Arc/Rc")]
    #![allow(dead_code, reason = "relocated helpers retain fields for layout")]
    #![allow(
        unfulfilled_lint_expectations,
        reason = "relocated #[expect] may be fulfilled at file or feature level"
    )]
    #![allow(
        clippy::undocumented_unsafe_blocks,
        reason = "relocated test bodies preserve original safety reasoning"
    )]
    #![allow(clippy::multiple_unsafe_ops_per_block, reason = "relocated tests group related unsafe ops")]
    #![allow(clippy::cast_possible_truncation, reason = "relocated tests use bounded values")]
    #![allow(clippy::cast_sign_loss, reason = "relocated tests use non-negative values")]
    #![allow(clippy::empty_drop, reason = "relocated tests use empty Drop impls to mark dropability")]
    #![allow(clippy::assertions_on_result_states, reason = "relocated tests deliberately assert error returns")]
    #![allow(clippy::empty_line_after_doc_comments, reason = "relocated test doc-comments")]

    use multitude::vec::Vec as ArenaVec;
    use multitude::{Arena, Box as ArenaBox, Rc};

    #[expect(dead_code, reason = "helper used by some relocated tests")]
    struct OneByteDrop(u8);
    impl Drop for OneByteDrop {
        fn drop(&mut self) {}
    }
    #[expect(unused_imports, reason = "relocated tests may reference common helpers")]
    use crate::common::{self, FailingAllocator, SendFailingAllocator};

    /// Kills `arena.rs:3197:55 - -> /` in `allocate_shared_layout`.
    /// Line 3197 computes `aligned_offset = aligned_addr - data_addr`.
    /// Mutated `/`: when `aligned_addr == data_addr` (the common case for
    /// pre-aligned bump cursors), `-` yields 0 but `/` yields 1, so the
    /// returned pointer becomes misaligned by 1 byte. This test exercises
    /// the path via the public DST-Arc API for a `[u128]` (align=16, non-
    /// Drop) and asserts the returned payload is properly aligned.
    #[test]
    fn allocate_shared_layout_high_align_offset_zero_preserved() {
        use core::alloc::Layout;
        let arena = multitude::Arena::new();
        // Repeat many times so we hit both fresh-chunk (offset 0) and
        // mid-chunk paths; misalignment of even one would fail an assert.
        for _ in 0..64 {
            let layout = Layout::array::<u128>(32).unwrap();
            let metadata: usize = 32;
            #[expect(
                clippy::multiple_unsafe_ops_per_block,
                reason = "single logical unsafe operation: the alloc_dst_arc DST initialization"
            )]
            // SAFETY: `init` writes 32 valid `u128`s through the fat pointer;
            // layout matches `[u128; 32]`; metadata is the slice length.
            let arc: multitude::Arc<[u128]> = unsafe {
                arena.alloc_dst_arc::<[u128]>(layout, metadata, |p: *mut [u128]| {
                    let base = p.cast::<u128>();
                    for i in 0_u128..32 {
                        core::ptr::write(base.add(i as usize), i);
                    }
                })
            };
            let raw_addr = arc.as_ptr().cast::<u128>() as usize;
            assert_eq!(raw_addr % 16, 0, "payload must be aligned to u128");
            assert_eq!(arc.len(), 32);
            for i in 0_u128..32 {
                assert_eq!(arc[i as usize], i);
            }
        }
    }

    /// Regression test for the `Vec<T: Drop> -> Box<[T]> -> Rc<[T]>`
    /// chain: previously `Box::<[T]>::into_rc()` aborted the process
    /// because `Vec::into_arena_box` didn't pre-install a noop drop
    /// entry that `retarget_box_drop_entry` requires. Now
    /// `Vec::into_arena_box` installs the noop entry for `T: Drop`.
    #[test]
    fn vec_into_arena_box_into_rc_drops_correctly() {
        use std::sync::Arc as StdArc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        let counter = StdArc::new(AtomicUsize::new(0));
        struct DT(StdArc<AtomicUsize>);
        impl Drop for DT {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::Relaxed);
            }
        }

        {
            let arena = multitude::Arena::new();
            let mut v: multitude::vec::Vec<DT, _> = multitude::vec::Vec::new_in(&arena);
            v.push(DT(counter.clone()));
            v.push(DT(counter.clone()));
            v.push(DT(counter.clone()));
            let b: multitude::Box<[DT]> = v.into_arena_box();
            let rc = multitude::Box::<[DT], _>::into_rc(b);
            assert_eq!(rc.len(), 3);
            // drop rc and arena
        }
        assert_eq!(counter.load(Ordering::Relaxed), 3);
    }

    /// Regression test for `Box<[T: Drop]>::into_rc()` on an empty
    /// slice: previously aborted the process because no drop entry
    /// was installed at alloc-time for `len == 0`. Now `into_rc`
    /// short-circuits the retarget for empty slices.
    #[test]
    fn empty_uninit_slice_box_into_rc_does_not_abort() {
        let arena = multitude::Arena::new();
        let b = arena.alloc_uninit_slice_box::<String>(0);
        // SAFETY: empty slice; no element to initialize.
        let init: multitude::Box<[String]> = unsafe { b.assume_init() };
        assert_eq!(init.len(), 0);
        let rc = multitude::Box::<[String], _>::into_rc(init);
        assert_eq!(rc.len(), 0);
    }

    #[test]
    fn into_arena_rc_empty_drop_type_takes_copy_path() {
        struct D;
        impl Drop for D {
            fn drop(&mut self) {}
        }
        let arena = Arena::new();
        let v: ArenaVec<'_, D> = arena.alloc_vec_with_capacity(4);
        assert_eq!(v.len(), 0);
        let rc: Rc<[D], _> = v.into_arena_rc();
        assert_eq!(rc.len(), 0);
    }

    #[test]
    fn into_arena_box_empty_drop_type_takes_copy_path() {
        struct D;
        impl Drop for D {
            fn drop(&mut self) {}
        }
        let arena = Arena::new();
        let v: ArenaVec<'_, D> = arena.alloc_vec_with_capacity(4);
        assert_eq!(v.len(), 0);
        let b: ArenaBox<[D], _> = v.into_arena_box();
        assert_eq!(b.len(), 0);
    }

    #[cfg(all(feature = "dst", feature = "stats"))]
    #[test]
    fn into_arena_rc_with_full_capacity_does_not_attempt_reclaim() {
        let arena = Arena::new();
        let mut v: ArenaVec<'_, u32> = arena.alloc_vec_with_capacity(4);
        for i in 0..4_u32 {
            v.push(i);
        }
        assert_eq!(v.len(), v.capacity());
        let rc: Rc<[u32], _> = v.into_arena_rc();
        assert_eq!(rc.len(), 4);
        // Drop and verify no spurious counters/double-reclaim.
        drop(rc);
    }

    #[test]
    fn into_arena_box_with_full_capacity_for_drop_type_no_reclaim() {
        let arena = Arena::new();
        let mut v: ArenaVec<'_, OneByteDrop> = arena.alloc_vec_with_capacity(4);
        for i in 0..4 {
            v.push(OneByteDrop(i));
        }
        assert_eq!(v.len(), v.capacity());
        let b: ArenaBox<[OneByteDrop], _> = v.into_arena_box();
        assert_eq!(b.len(), 4);
    }

    #[test]
    fn into_arena_box_with_full_capacity_for_non_drop_type_no_reclaim() {
        let arena = Arena::new();
        let mut v: ArenaVec<'_, u32> = arena.alloc_vec_with_capacity(4);
        for i in 0..4 {
            v.push(i);
        }
        assert_eq!(v.len(), v.capacity());
        let b: ArenaBox<[u32], _> = v.into_arena_box();
        assert_eq!(b.len(), 4);
    }

    #[test]
    fn into_arena_box_with_unused_tail_reclaims() {
        let arena = Arena::new();
        let mut v: ArenaVec<'_, u32> = arena.alloc_vec_with_capacity(8);
        v.push(1);
        v.push(2);
        let b: ArenaBox<[u32], _> = v.into_arena_box();
        assert_eq!(b.len(), 2);
        // After reclaim, a fresh small allocation should fit immediately
        // after the box without needing a fresh chunk.
        let _r: Rc<u32> = arena.alloc_rc(99);
    }

    #[test]
    fn into_arena_box_copy_walks_all_elements() {
        // Force the copy path by using a ZST; the copy fallback is the
        // only code that runs for `elem_size == 0` — but a ZST never enters
        // `into_arena_box_copy`'s element-by-element loop because the buffer
        // has no real backing. Use the empty-builder branch instead: a Vec
        // with cap==0 has no buffer either. So the simplest way to exercise
        // line 911 is via `into_arena_box` on a Drop type whose installation
        // fails — that path also routes to `into_arena_box_copy`. Easier:
        // construct via the Vec macro with explicit copy fallback by using
        // a Drop type and a vec built across multiple chunks (forcing the
        // slice DropEntry install to fail).
        //
        // Simpler still: allocate a Drop-type Vec that needs a buffer
        // relocation between push and freeze. After `realloc` the buffer
        // moves off the bump cursor; `try_install_slice_drop_entry` will
        // fail (chunk no longer current at that offset) and fall back to
        // `into_arena_box_copy`, which is the function we want to hit.
        use core::cell::Cell;
        struct D<'a> {
            seen: &'a Cell<u32>,
            idx: u32,
        }
        impl Drop for D<'_> {
            fn drop(&mut self) {
                self.seen.set(self.seen.get() | (1_u32 << self.idx));
            }
        }
        let mask = Cell::new(0_u32);
        let arena = Arena::new();
        {
            let mut v: ArenaVec<'_, D<'_>> = arena.alloc_vec_with_capacity(2);
            v.push(D { seen: &mask, idx: 0 });
            v.push(D { seen: &mask, idx: 1 });
            // Force a relocation by pushing one more (cap=2 → realloc to 4).
            // Then a subsequent allocation steals the spot, so `try_install`
            // for the freeze likely fails.
            v.push(D { seen: &mask, idx: 2 });
            let _other: Rc<u64> = arena.alloc_rc(0);
            let _b: ArenaBox<[D<'_>], _> = v.into_arena_box();
        }
        drop(arena);
        // All 3 elements must have been seen exactly once (mask 0b111).
        assert_eq!(mask.get(), 0b111, "all elements should drop exactly once");
    }

    #[test]
    fn into_arena_box_copy_advances_consumed_index() {
        use std::sync::Arc as StdArc;
        use std::sync::atomic::{AtomicU32, Ordering};

        struct D {
            idx: u32,
            seen: StdArc<AtomicU32>,
        }
        impl Drop for D {
            fn drop(&mut self) {
                self.seen.fetch_or(1_u32 << (self.idx % 32), Ordering::Relaxed);
            }
        }

        let seen = StdArc::new(AtomicU32::new(0));
        {
            let arena = Arena::new();
            // 16-byte D; default max_normal_alloc = 16 KiB. with_capacity(1100)
            // requests 17.6 KiB > max_normal_alloc → buffer goes to oversized
            // chunk, install fails, into_arena_box falls back to the copy path.
            let mut v: ArenaVec<'_, D> = arena.alloc_vec_with_capacity(1100);
            for i in 0..1100_u32 {
                v.push(D {
                    idx: i,
                    seen: seen.clone(),
                });
            }
            let b: ArenaBox<[D], _> = v.into_arena_box();
            for (i, d) in b.iter().enumerate() {
                assert_eq!(d.idx, i as u32, "element {i} should have idx {i}");
            }
            drop(b);
        }
        assert_eq!(seen.load(Ordering::Relaxed), u32::MAX);
    }

    #[test]
    fn box_slice_into_rc_with_drop_type_runs_drop_once() {
        use std::sync::Arc as StdArc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        let counter = StdArc::new(AtomicUsize::new(0));
        struct D(StdArc<AtomicUsize>);
        impl Drop for D {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::Relaxed);
            }
        }

        let arena = Arena::new();
        {
            let mut v: ArenaVec<'_, D> = arena.alloc_vec_with_capacity(3);
            for _ in 0..3 {
                v.push(D(counter.clone()));
            }
            let b: ArenaBox<[D]> = v.into_arena_box();
            let _rc = multitude::Box::<[D], _>::into_rc(b);
        }
        drop(arena);
        assert_eq!(counter.load(Ordering::Relaxed), 3);
    }

    #[test]
    fn dst_arc_rejects_excessive_alignment_via_layout() {
        let arena = Arena::new();
        let layout = core::alloc::Layout::from_size_align(64, 32 * 1024).unwrap();
        // SAFETY: validation runs before any user-visible state mutation.
        let result = unsafe { arena.try_alloc_dst_arc::<[u8]>(layout, 64, |_| {}) };
        result.unwrap_err();
    }
}