fastarena 0.2.0

A zero-dependency, bump-pointer arena allocator with RAII transactions, nested savepoints, optional LIFO destructor tracking, and ArenaVec — built for compilers, storage engines, and high-throughput request-scoped workloads.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
use std::mem::{self, MaybeUninit};
use std::ptr::NonNull;

use super::block::{align_up, Block, MIN_BLOCK_ALIGN};
use super::boxed::ArenaBox;
use super::stats::ArenaStats;
use crate::util::{
    inline_vec::InlineVec,
    transaction::{run_with_transaction, run_with_transaction_infallible, Transaction},
};

#[cfg(feature = "drop-tracking")]
use crate::util::drop_registry::DropRegistry;

/// Floor for block allocation — prevents degenerate tiny blocks.
const MIN_BLOCK_SIZE: usize = 64;
/// Default first-block size (64 KiB). Chosen to cover typical per-request
/// arena usage without an early spill to a second block.
const DEFAULT_BLOCK_SIZE: usize = 64 * 1_024;
/// Hard ceiling for a single block (16 MiB). Blocks larger than this add
/// pressure to the OS virtual-memory subsystem with no locality benefit.
const MAX_BLOCK_SIZE: usize = 16 * 1_024 * 1_024;
/// Number of block pointers stored inline before spilling to the heap.
/// Most workloads stay within this limit, avoiding a heap alloc for the
/// block list itself.
const BLOCKS_INLINE_CAP: usize = 8;

/// Cache-line size on x86-64 / ARM64 hardware.
pub(crate) const CACHE_LINE_SIZE: usize = 64;

/// An opaque snapshot of arena state used by [`Arena::rewind`].
///
/// Obtained via [`Arena::checkpoint`]. Must only be passed back to the arena
/// that produced it — using it with a different arena panics.
#[derive(Debug, Clone, Copy)]
#[must_use = "checkpoint is useless unless passed to Arena::rewind"]
pub struct Checkpoint {
    pub(crate) block_idx: usize,
    pub(crate) offset: usize,
    pub(crate) bytes_allocated: usize,
    #[cfg(feature = "drop-tracking")]
    pub(crate) drop_registry_len: usize,
}

impl std::fmt::Display for Checkpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Checkpoint(block={}, offset={}, bytes={})",
            self.block_idx, self.offset, self.bytes_allocated
        )
    }
}

/// A bump-pointer arena allocator with RAII transactions, checkpoint/rewind,
/// and zero-cost reset/reuse.
///
/// # Allocation model
///
/// Every allocation method takes `&mut self`. The borrow checker statically
/// prevents `rewind` or `reset` while any live reference exists — there is no
/// runtime cost for this guarantee.
///
/// # Destructor behaviour
///
/// Without the `drop-tracking` feature, destructors are **never called** for
/// arena-allocated values. This is intentional: the performance advantage of
/// arena allocation comes from bulk reclamation. Enable `drop-tracking` to opt
/// in to LIFO destructor execution on `reset` / `rewind`.
///
/// # When NOT to use an arena
///
/// - Objects that need independent lifetimes (use `Box` or `Rc`).
/// - Frequent arbitrary-order removal (use a slab allocator).
/// - Multi-threaded access (wrap in a `Mutex` or use thread-local arenas).
///
/// # Thread-local pattern
///
/// ```ignore
/// thread_local! {
///     static ARENA: RefCell<Arena> = RefCell::new(Arena::with_capacity(64 * 1024));
/// }
/// fn handle_request(req: &Request) {
///     ARENA.with(|a| {
///         let mut arena = a.borrow_mut();
///         process(&mut arena, req);
///         arena.reset();
///     })
/// }
/// ```
///
/// # Multiple allocations and the borrow checker
///
/// All `alloc*` methods return `&mut T`. This prevents making multiple allocations
/// simultaneously because the borrow checker sees the arena as mutably borrowed.
/// The following code does NOT compile:
///
/// ```ignore
/// let mut arena = Arena::new();
/// let x = arena.alloc(1i32);  // &mut i32
/// let y = arena.alloc(2i32);  // ERROR: cannot borrow arena as mutable more than once
/// ```
///
/// **Workarounds:**
///
/// 1. **Immediate consumption** — transform the value before allocating another:
///    ```rust
///    use fastarena::Arena;
///
///    let mut arena = Arena::new();
///    let x = arena.alloc(1i32);
///    let sum = *x + 10;  // consume x
///    let y = arena.alloc(sum);
///    ```
///
/// 2. **Store as raw pointer** — convert the reference to a raw pointer after allocation:
///    ```rust
///    use fastarena::Arena;
///
///    let mut arena = Arena::new();
///    let x: *mut i32 = arena.alloc(1i32) as *mut _;
///    let y = arena.alloc(2i32);
///    // use x and y independently
///    ```
///
/// 3. **Use [`crate::vec::ArenaVec`]** — for multiple items of the same type:
///    ```rust
///    use fastarena::{Arena, ArenaVec};
///
///    let mut arena = Arena::new();
///    let mut vec = ArenaVec::new(&mut arena);
///    vec.push(1);
///    vec.push(2);
///    let slice = vec.finish();  // &mut [i32]
///    ```
///
/// 4. **Use [`ArenaBox<T>`]** — for owned allocation with drop semantics:
///    ```rust
///    use fastarena::{Arena, ArenaBox};
///
///    let mut arena = Arena::new();
///    let x = arena.alloc_box(1i32);
///    // x has ownership semantics - can be moved or dropped
///    assert_eq!(*x, 1);
///    ```
pub struct Arena {
    blocks: InlineVec<Block, BLOCKS_INLINE_CAP>,
    pub(crate) current: usize,
    next_block_size: usize,
    pub(crate) bytes_allocated: usize,
    bytes_reserved: usize,
    pub(crate) txn_depth: usize,
    #[cfg(feature = "drop-tracking")]
    pub(crate) drop_registry: DropRegistry,
    #[cfg(not(feature = "drop-tracking"))]
    _drop_registry: (),
    pub(crate) cur_base: *mut u8,
    pub(crate) cur_ptr: *mut u8,
    /// End pointer of the current block (= cur_base + capacity). Cached to
    /// eliminate block array access on every fast-path allocation.
    pub(crate) cur_end: *mut u8,
    /// Highest block index ever reached — used by `reset()` to iterate only
    /// the blocks that were actually touched, instead of all retained blocks.
    high_water_mark: usize,
    /// Maximum contiguous free space across all retained blocks (post-current).
    /// Used by `alloc_slow` to skip the block scan entirely when no retained
    /// block can satisfy the request. Updated lazily on block transitions.
    largest_remaining: usize,
    /// Index of the block with the largest remaining space (post-current).
    /// Used for incremental updates instead of scanning all blocks.
    largest_remaining_idx: usize,
}

impl Arena {
    /// Create an arena with a 64 KiB initial block.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let x = arena.alloc(42u64);
    /// assert_eq!(*x, 42);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_BLOCK_SIZE)
    }

    /// Create an arena with a custom initial block size.
    ///
    /// Choose a value close to expected peak usage to avoid early block
    /// chaining.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::with_capacity(1024 * 1024); // 1 MiB
    /// let _ = arena.alloc(1u64);
    /// assert_eq!(arena.stats().bytes_reserved, 1024 * 1024);
    /// ```
    #[must_use]
    pub fn with_capacity(initial_bytes: usize) -> Self {
        let size = initial_bytes.max(MIN_BLOCK_SIZE);
        let block = Block::new(size, MIN_BLOCK_ALIGN);
        let base = block.base;
        let mut blocks: InlineVec<Block, BLOCKS_INLINE_CAP> = InlineVec::new();
        blocks.push(block);
        Arena {
            blocks,
            current: 0,
            next_block_size: size.saturating_mul(2).min(MAX_BLOCK_SIZE),
            bytes_allocated: 0,
            bytes_reserved: size,
            txn_depth: 0,
            #[cfg(feature = "drop-tracking")]
            drop_registry: DropRegistry::new(),
            #[cfg(not(feature = "drop-tracking"))]
            _drop_registry: (),
            cur_base: base,
            cur_ptr: base,
            cur_end: unsafe { base.add(size) },
            high_water_mark: 0,
            largest_remaining: 0,
            largest_remaining_idx: 0,
        }
    }
}

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

impl std::fmt::Debug for Arena {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let stats = self.stats();
        f.debug_struct("Arena")
            .field("bytes_allocated", &stats.bytes_allocated)
            .field("bytes_reserved", &stats.bytes_reserved)
            .field("block_count", &stats.block_count)
            .field("txn_depth", &self.txn_depth)
            .finish()
    }
}

impl Arena {
    /// Allocate a value of type `T`, returning an exclusive reference.
    ///
    /// Without `drop-tracking`, the destructor of `T` is never called.
    /// Arena memory is reclaimed in bulk by [`reset`](Arena::reset) or when
    /// the arena itself is dropped.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let x: &mut u64 = arena.alloc(42);
    /// assert_eq!(*x, 42);
    /// *x = 100;
    /// assert_eq!(*x, 100);
    /// ```
    #[inline]
    pub fn alloc<T>(&mut self, val: T) -> &mut T {
        if mem::size_of::<T>() == 0 {
            return unsafe { &mut *NonNull::dangling().as_ptr() };
        }
        let ptr = self.alloc_raw_inner(mem::size_of::<T>(), mem::align_of::<T>());
        unsafe {
            let typed = ptr.as_ptr().cast::<T>();
            typed.write(val);
            #[cfg(feature = "drop-tracking")]
            self.drop_registry.register(typed);
            &mut *typed
        }
    }

    /// Allocate a contiguous slice of `T` from an `ExactSizeIterator`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let slice = arena.alloc_slice(0u32..5);
    /// assert_eq!(slice, &[0, 1, 2, 3, 4]);
    /// ```
    /// # Panics
    ///
    /// Panics if the iterator's `ExactSizeIterator::len` lies and more elements
    /// are produced than reported.
    #[inline]
    pub fn alloc_slice<T, I>(&mut self, iter: I) -> &mut [T]
    where
        I: IntoIterator<Item = T>,
        I::IntoIter: ExactSizeIterator,
    {
        let mut iter = iter.into_iter();
        let len = iter.len();
        if len == 0 {
            return &mut [];
        }
        let total = mem::size_of::<T>().checked_mul(len).expect("overflow");
        let ptr = self.alloc_raw_inner(total, mem::align_of::<T>());
        unsafe {
            let start = ptr.as_ptr().cast::<T>();
            Self::write_slice_bulk::<T, _>(start, &mut iter, len, total);
            #[cfg(feature = "drop-tracking")]
            self.drop_registry.register_slice(start, len);
            std::slice::from_raw_parts_mut(start, len)
        }
    }

    /// Allocate a contiguous slice from a slice of `Copy` items using a single memcpy.
    /// Significantly faster than `alloc_slice` for small-to-medium `Copy` types.
    ///
    /// # Panics
    ///
    /// Panics if the system is out of memory.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let src: &[u64] = &[1, 2, 3, 4];
    /// let dst = arena.alloc_slice_copy(src);
    /// assert_eq!(dst, &[1, 2, 3, 4]);
    /// ```
    #[inline]
    pub fn alloc_slice_copy<T: Copy>(&mut self, src: &[T]) -> &mut [T] {
        let len = src.len();
        if len == 0 {
            return &mut [];
        }
        let total = mem::size_of::<T>().checked_mul(len).expect("overflow");
        let ptr = self.alloc_raw_inner(total, mem::align_of::<T>());
        unsafe {
            let dst = ptr.as_ptr().cast::<T>();
            std::ptr::copy_nonoverlapping(src.as_ptr(), dst, len);
            #[cfg(feature = "drop-tracking")]
            self.drop_registry.register_slice(dst, len);
            std::slice::from_raw_parts_mut(dst, len)
        }
    }

    /// Copy a string slice into the arena and return a reference to it.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let s: &str = arena.alloc_str("hello world");
    /// assert_eq!(s, "hello world");
    /// ```
    #[inline(always)]
    pub fn alloc_str(&mut self, s: &str) -> &str {
        if s.is_empty() {
            return "";
        }
        // align=1, so cur_ptr needs no adjustment - dedicated fast path
        let new_end = (self.cur_ptr as usize) + s.len();
        if new_end <= self.cur_end as usize {
            let ptr = self.cur_ptr;
            self.cur_ptr = unsafe { self.cur_ptr.add(s.len()) };
            unsafe {
                std::ptr::copy_nonoverlapping(s.as_ptr(), ptr, s.len());
                return std::str::from_utf8_unchecked(std::slice::from_raw_parts(ptr, s.len()));
            }
        }
        self.alloc_slow_str(s)
    }

    #[cold]
    fn alloc_slow_str(&mut self, s: &str) -> &str {
        let ptr = self.alloc_raw_inner(s.len(), 1);
        unsafe {
            std::ptr::copy_nonoverlapping(s.as_ptr(), ptr.as_ptr(), s.len());
            std::str::from_utf8_unchecked(std::slice::from_raw_parts(ptr.as_ptr(), s.len()))
        }
    }

    /// Allocate space for a `T` without initialising it.
    ///
    /// The caller must fully initialise the value before it can be observed.
    ///
    /// ```rust
    /// use fastarena::Arena;
    /// let mut arena = Arena::new();
    /// let slot = arena.alloc_uninit::<u64>();
    /// slot.write(42);
    /// let val: &u64 = unsafe { slot.assume_init_ref() };
    /// assert_eq!(*val, 42);
    /// ```
    #[inline]
    pub fn alloc_uninit<T>(&mut self) -> &mut MaybeUninit<T> {
        let size = mem::size_of::<T>();
        let align = mem::align_of::<T>();
        if size == 0 {
            return unsafe { &mut *NonNull::dangling().as_ptr() };
        }
        let ptr = self.alloc_raw_inner(size, align);
        unsafe { &mut *ptr.as_ptr().cast::<MaybeUninit<T>>() }
    }

    /// Allocate an owned value `T` from the arena, returning an [`ArenaBox`].
    ///
    /// Unlike `alloc()` which returns `&mut T`, `alloc_box()` returns `ArenaBox<T>`.
    /// This provides ownership semantics, but note that the arena still uses interior
    /// mutability internally.
    ///
    /// Note: The arena must not be reset or rewound while any `ArenaBox` is still in use.
    #[inline]
    pub fn alloc_box<T>(&mut self, val: T) -> ArenaBox<'_, T> {
        ArenaBox::new(self, val)
    }

    /// Allocate `size` bytes with the given `align` alignment, initialized to zero.
    ///
    /// # Panics
    ///
    /// Panics if `align` is not a power of two or the system is out of memory.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let ptr = arena.alloc_zeroed(32, 8);
    /// let buf = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), 32) };
    /// assert!(buf.iter().all(|&b| b == 0));
    /// ```
    #[inline]
    pub fn alloc_zeroed(&mut self, size: usize, align: usize) -> NonNull<u8> {
        if size == 0 {
            return NonNull::dangling();
        }
        let ptr = self.alloc_raw(size, align);
        unsafe { ptr.as_ptr().write_bytes(0, size) };
        ptr
    }

    /// Allocate `size` bytes aligned to a 64-byte cache line boundary.
    ///
    /// This is useful for data structures that benefit from cache-line-aligned
    /// access, such as SIMD operations or lock-free data structures.
    ///
    /// # Panics
    ///
    /// Panics if the system is out of memory.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let ptr = arena.alloc_cache_aligned(128);
    /// assert_eq!(ptr.as_ptr() as usize % 64, 0);
    /// ```
    #[inline]
    pub fn alloc_cache_aligned(&mut self, size: usize) -> NonNull<u8> {
        self.alloc_raw(size, CACHE_LINE_SIZE)
    }

    /// Low-level allocation of `size` uninitialised bytes at `align` alignment.
    ///
    /// # Panics
    /// Panics if `align` is not a power of two or the system is out of memory.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let ptr = arena.alloc_raw(64, 32);
    /// assert_eq!(ptr.as_ptr() as usize % 32, 0);
    /// ```
    #[inline]
    pub fn alloc_raw(&mut self, size: usize, align: usize) -> NonNull<u8> {
        assert!(align.is_power_of_two(), "align must be a power of two");
        if size == 0 {
            return NonNull::dangling();
        }
        self.alloc_raw_inner(size, align)
    }
}

impl Arena {
    /// Fallible variant of [`alloc`](Arena::alloc). Returns `None` on OOM.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let x = arena.try_alloc(42u64);
    /// assert_eq!(*x.unwrap(), 42);
    /// ```
    #[inline]
    #[must_use]
    pub fn try_alloc<T>(&mut self, val: T) -> Option<&mut T> {
        if mem::size_of::<T>() == 0 {
            return Some(unsafe { &mut *NonNull::dangling().as_ptr() });
        }
        let ptr = self.try_alloc_raw_inner(mem::size_of::<T>(), mem::align_of::<T>())?;
        Some(unsafe {
            let typed = ptr.as_ptr().cast::<T>();
            typed.write(val);
            #[cfg(feature = "drop-tracking")]
            self.drop_registry.register(typed);
            &mut *typed
        })
    }

    /// Fallible variant of [`alloc_slice`](Arena::alloc_slice).
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let s = arena.try_alloc_slice(0u32..4);
    /// assert_eq!(s.unwrap(), &[0, 1, 2, 3]);
    /// ```
    #[inline]
    #[must_use]
    pub fn try_alloc_slice<T, I>(&mut self, iter: I) -> Option<&mut [T]>
    where
        I: IntoIterator<Item = T>,
        I::IntoIter: ExactSizeIterator,
    {
        let mut iter = iter.into_iter();
        let len = iter.len();
        if len == 0 {
            return Some(&mut []);
        }
        let total = mem::size_of::<T>().checked_mul(len)?;
        let ptr = self.try_alloc_raw_inner(total, mem::align_of::<T>())?;
        Some(unsafe {
            let start = ptr.as_ptr().cast::<T>();
            Self::write_slice_bulk::<T, _>(start, &mut iter, len, total);
            #[cfg(feature = "drop-tracking")]
            self.drop_registry.register_slice(start, len);
            std::slice::from_raw_parts_mut(start, len)
        })
    }

    /// Fallible variant of [`alloc_str`](Arena::alloc_str).
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let s = arena.try_alloc_str("hello");
    /// assert_eq!(s, Some("hello"));
    /// ```
    #[inline(always)]
    #[must_use]
    pub fn try_alloc_str(&mut self, s: &str) -> Option<&str> {
        if s.is_empty() {
            return Some("");
        }
        // Same bump fast path as [`alloc_str`](Self::alloc_str); align = 1.
        let new_end = (self.cur_ptr as usize).checked_add(s.len())?;
        if new_end <= self.cur_end as usize {
            let ptr = self.cur_ptr;
            self.cur_ptr = unsafe { self.cur_ptr.add(s.len()) };
            unsafe {
                core::ptr::copy_nonoverlapping(s.as_ptr(), ptr, s.len());
                return Some(core::str::from_utf8_unchecked(core::slice::from_raw_parts(
                    ptr,
                    s.len(),
                )));
            }
        }
        self.try_alloc_slow_str(s)
    }

    #[cold]
    fn try_alloc_slow_str(&mut self, s: &str) -> Option<&str> {
        let ptr = self.try_alloc_raw_inner(s.len(), 1)?;
        unsafe {
            core::ptr::copy_nonoverlapping(s.as_ptr(), ptr.as_ptr(), s.len());
            Some(core::str::from_utf8_unchecked(core::slice::from_raw_parts(
                ptr.as_ptr(),
                s.len(),
            )))
        }
    }

    /// Fallible variant of [`alloc_raw`](Arena::alloc_raw).
    ///
    /// # Panics
    ///
    /// Panics if `align` is not a power of two.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let ptr = arena.try_alloc_raw(128, 64);
    /// assert!(ptr.is_some());
    /// assert_eq!(ptr.unwrap().as_ptr() as usize % 64, 0);
    /// ```
    #[inline]
    #[must_use]
    pub fn try_alloc_raw(&mut self, size: usize, align: usize) -> Option<NonNull<u8>> {
        assert!(align.is_power_of_two(), "align must be a power of two");
        if size == 0 {
            return Some(NonNull::dangling());
        }
        self.try_alloc_raw_inner(size, align)
    }

    /// Fallible variant of [`alloc_slice_copy`](Arena::alloc_slice_copy).
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let s = arena.try_alloc_slice_copy(&[10u64, 20, 30]);
    /// assert_eq!(s.unwrap(), &[10, 20, 30]);
    /// ```
    #[inline]
    #[must_use]
    pub fn try_alloc_slice_copy<T: Copy>(&mut self, src: &[T]) -> Option<&mut [T]> {
        let len = src.len();
        if len == 0 {
            return Some(&mut []);
        }
        let total = mem::size_of::<T>().checked_mul(len)?;
        let ptr = self.try_alloc_raw_inner(total, mem::align_of::<T>())?;
        unsafe {
            let dst = ptr.as_ptr().cast::<T>();
            std::ptr::copy_nonoverlapping(src.as_ptr(), dst, len);
            #[cfg(feature = "drop-tracking")]
            self.drop_registry.register_slice(dst, len);
            Some(std::slice::from_raw_parts_mut(dst, len))
        }
    }

    /// Fallible variant of [`alloc_zeroed`](Arena::alloc_zeroed).
    ///
    /// # Panics
    ///
    /// Panics if `align` is not a power of two.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let ptr = arena.try_alloc_zeroed(64, 8);
    /// assert!(ptr.is_some());
    /// let buf = unsafe { std::slice::from_raw_parts(ptr.unwrap().as_ptr(), 64) };
    /// assert!(buf.iter().all(|&b| b == 0));
    /// ```
    #[inline]
    #[must_use]
    pub fn try_alloc_zeroed(&mut self, size: usize, align: usize) -> Option<NonNull<u8>> {
        assert!(align.is_power_of_two(), "align must be a power of two");
        if size == 0 {
            return Some(NonNull::dangling());
        }
        let ptr = self.try_alloc_raw_inner(size, align)?;
        unsafe { ptr.as_ptr().write_bytes(0, size) };
        Some(ptr)
    }

    /// Fallible variant of [`alloc_cache_aligned`](Arena::alloc_cache_aligned).
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let ptr = arena.try_alloc_cache_aligned(128);
    /// assert!(ptr.is_some());
    /// assert_eq!(ptr.unwrap().as_ptr() as usize % 64, 0);
    /// ```
    #[inline]
    #[must_use]
    pub fn try_alloc_cache_aligned(&mut self, size: usize) -> Option<NonNull<u8>> {
        self.try_alloc_raw(size, CACHE_LINE_SIZE)
    }

    /// Allocate a slice of `n` uninitialized values from the arena.
    ///
    /// Useful when you need to allocate space for `n` elements and initialize
    /// them later (e.g., from an iterator or in-place construction).
    ///
    /// # Safety
    ///
    /// The returned slice contains [`MaybeUninit<T>`]. The caller must
    /// initialize every element before reading them as `T`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    /// use std::mem::MaybeUninit;
    ///
    /// let mut arena = Arena::new();
    /// let slice = arena.alloc_slice_uninit::<u32>(16);
    /// for (i, slot) in slice.iter_mut().enumerate() {
    ///     slot.write(i as u32);
    /// }
    /// // Safe to read now: every slot is initialized.
    /// let init: &[u32] = unsafe { std::mem::transmute::<&[MaybeUninit<u32>], &[u32]>(slice) };
    /// assert_eq!(init.len(), 16);
    /// assert_eq!(init[5], 5);
    /// ```
    #[inline]
    pub fn alloc_slice_uninit<T>(&mut self, n: usize) -> &mut [MaybeUninit<T>] {
        if n == 0 || mem::size_of::<T>() == 0 {
            // ZSTs and zero-length slices share a dangling but well-aligned address.
            return unsafe {
                std::slice::from_raw_parts_mut(NonNull::<MaybeUninit<T>>::dangling().as_ptr(), n)
            };
        }
        let total = mem::size_of::<T>()
            .checked_mul(n)
            .expect("alloc_slice_uninit: size overflow");
        let ptr = self.alloc_raw_inner(total, mem::align_of::<T>());
        unsafe { std::slice::from_raw_parts_mut(ptr.as_ptr().cast::<MaybeUninit<T>>(), n) }
    }

    /// Fallible variant of [`alloc_slice_uninit`](Arena::alloc_slice_uninit).
    ///
    /// Returns `None` if the system is out of memory or `n * size_of::<T>()`
    /// would overflow `usize`.
    #[inline]
    #[must_use]
    pub fn try_alloc_slice_uninit<T>(&mut self, n: usize) -> Option<&mut [MaybeUninit<T>]> {
        if n == 0 || mem::size_of::<T>() == 0 {
            return Some(unsafe {
                std::slice::from_raw_parts_mut(NonNull::<MaybeUninit<T>>::dangling().as_ptr(), n)
            });
        }
        let total = mem::size_of::<T>().checked_mul(n)?;
        let ptr = self.try_alloc_raw_inner(total, mem::align_of::<T>())?;
        Some(unsafe { std::slice::from_raw_parts_mut(ptr.as_ptr().cast::<MaybeUninit<T>>(), n) })
    }

    /// Allocate a slice of `n` elements, each cloned from `val`.
    ///
    /// Equivalent to `arena.alloc_slice(std::iter::repeat(val).take(n))`,
    /// but specialised: avoids constructing the iterator and skips the per-
    /// element call when `T: Copy` (the compiler will rewrite the loop into
    /// a memset-style fill).
    ///
    /// # Panics
    ///
    /// Panics if the system is out of memory or `n * size_of::<T>()` overflows.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let buf: &mut [u32] = arena.alloc_slice_fill(8, 7);
    /// assert_eq!(buf, &[7u32; 8]);
    /// ```
    #[inline]
    pub fn alloc_slice_fill<T: Clone>(&mut self, n: usize, val: T) -> &mut [T] {
        if n == 0 || mem::size_of::<T>() == 0 {
            // ZSTs share a dangling pointer; let `val` drop normally.
            return unsafe { std::slice::from_raw_parts_mut(NonNull::<T>::dangling().as_ptr(), n) };
        }
        let total = mem::size_of::<T>()
            .checked_mul(n)
            .expect("alloc_slice_fill: size overflow");
        let ptr = self.alloc_raw_inner(total, mem::align_of::<T>());
        let dst = ptr.as_ptr().cast::<T>();
        // SAFETY: `dst` points to `n` aligned, uninitialized slots.
        unsafe {
            // Fill all but the last with clones, then move the original.
            for i in 0..n.saturating_sub(1) {
                dst.add(i).write(val.clone());
            }
            dst.add(n - 1).write(val);
            #[cfg(feature = "drop-tracking")]
            self.drop_registry.register_slice(dst, n);
            std::slice::from_raw_parts_mut(dst, n)
        }
    }

    /// Allocate a slice of `n` elements, each filled with `T::default()`.
    ///
    /// # Panics
    ///
    /// Panics if the system is out of memory or `n * size_of::<T>()` overflows.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let buf: &mut [u64] = arena.alloc_slice_default(4);
    /// assert_eq!(buf, &[0u64, 0, 0, 0]);
    /// ```
    #[inline]
    pub fn alloc_slice_default<T: Default>(&mut self, n: usize) -> &mut [T] {
        if n == 0 || mem::size_of::<T>() == 0 {
            return unsafe { std::slice::from_raw_parts_mut(NonNull::<T>::dangling().as_ptr(), n) };
        }
        let total = mem::size_of::<T>()
            .checked_mul(n)
            .expect("alloc_slice_default: size overflow");
        let ptr = self.alloc_raw_inner(total, mem::align_of::<T>());
        let dst = ptr.as_ptr().cast::<T>();
        // SAFETY: `dst` points to `n` aligned, uninitialized slots.
        unsafe {
            for i in 0..n {
                dst.add(i).write(T::default());
            }
            #[cfg(feature = "drop-tracking")]
            self.drop_registry.register_slice(dst, n);
            std::slice::from_raw_parts_mut(dst, n)
        }
    }

    /// Allocate a `T` produced by the given closure.
    ///
    /// Identical to [`alloc`](Arena::alloc) but avoids materializing `T` on
    /// the stack first: the value is constructed directly into arena memory.
    /// Use this for large `T` to avoid an extra stack copy.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let v: &mut [u8; 1024] = arena.alloc_with(|| [0u8; 1024]);
    /// assert_eq!(v.len(), 1024);
    /// ```
    #[inline]
    pub fn alloc_with<T, F>(&mut self, f: F) -> &mut T
    where
        F: FnOnce() -> T,
    {
        // Note: in practice the optimiser already places returned values
        // directly into the destination via NRVO. This wrapper just makes
        // intent explicit and matches bumpalo's API for portability.
        self.alloc(f())
    }
}

impl Arena {
    /// Bytes left in the current block before a new block must be allocated.
    ///
    /// This is the upper bound on the size of the next *fast-path* allocation
    /// for a `MIN_BLOCK_ALIGN`-aligned type. Larger requests or higher
    /// alignment may take the slow path even when this returns a non-zero
    /// value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::with_capacity(1024);
    /// assert!(arena.remaining() >= 1024);
    /// let _ = arena.alloc_slice_copy(&[0u8; 100]);
    /// assert!(arena.remaining() <= 924);
    /// ```
    #[inline(always)]
    #[must_use]
    pub fn remaining(&self) -> usize {
        (self.cur_end as usize).saturating_sub(self.cur_ptr as usize)
    }

    /// Returns `true` if `ptr` lies inside any block currently owned by this
    /// arena.
    ///
    /// O(blocks). Useful for debugging, sanitizer integration, and
    /// safety-critical assertions.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let p: *const u8 = arena.alloc(42u64) as *const u64 as *const u8;
    /// assert!(arena.contains_ptr(p));
    /// let stack_local = 0u64;
    /// assert!(!arena.contains_ptr((&stack_local as *const u64).cast::<u8>()));
    /// ```
    #[must_use]
    pub fn contains_ptr(&self, ptr: *const u8) -> bool {
        let p = ptr as usize;
        for i in 0..self.blocks.len() {
            let block = self.blocks.get(i);
            let base = block.base as usize;
            if p >= base && p < base.saturating_add(block.capacity) {
                return true;
            }
        }
        false
    }
}

impl Arena {
    /// Capture the current allocation position as an opaque [`Checkpoint`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let _ = arena.alloc(1u64);
    /// let cp = arena.checkpoint();
    /// let _ = arena.alloc(2u64);
    /// arena.rewind(cp);
    /// assert_eq!(arena.stats().bytes_allocated, 8);
    /// ```
    #[inline(always)]
    pub fn checkpoint(&self) -> Checkpoint {
        let current_offset = self.cur_ptr as usize - self.cur_base as usize;
        Checkpoint {
            block_idx: self.current,
            offset: current_offset,
            bytes_allocated: self.bytes_allocated + current_offset,
            #[cfg(feature = "drop-tracking")]
            drop_registry_len: self.drop_registry.len(),
        }
    }

    /// Roll back all allocations made after `cp` was taken.
    ///
    /// Blocks opened after the checkpoint have their offsets reset to zero and
    /// are retained for immediate reuse — no OS calls are made. If the
    /// `drop-tracking` feature is enabled, destructors for post-checkpoint
    /// objects are run in LIFO order before memory is reclaimed.
    ///
    /// # Panics
    /// Panics if `cp` was not produced by this arena.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let cp = arena.checkpoint();
    /// let x = arena.alloc(0xDEADu64);
    /// arena.rewind(cp);
    /// // x is now dangling — memory reclaimed for reuse
    /// assert_eq!(arena.stats().bytes_allocated, 0);
    /// ```
    pub fn rewind(&mut self, cp: Checkpoint) {
        assert!(
            cp.block_idx < self.blocks.len(),
            "rewind: checkpoint block_idx {} out of range (arena has {} blocks)",
            cp.block_idx,
            self.blocks.len()
        );
        debug_assert!(
            cp.offset <= self.blocks.get(cp.block_idx).capacity,
            "rewind: checkpoint offset {} exceeds block capacity {}",
            cp.offset,
            self.blocks.get(cp.block_idx).capacity
        );

        #[cfg(feature = "drop-tracking")]
        self.drop_registry.run_drops_until(cp.drop_registry_len);

        for i in (cp.block_idx + 1)..=self.current {
            self.blocks.get_mut(i).offset = 0;
        }
        self.blocks.get_mut(cp.block_idx).offset = cp.offset;
        self.bytes_allocated = cp.bytes_allocated - cp.offset;
        self.set_current_block(cp.block_idx);
    }

    /// Reset the entire arena so all memory is available for reuse.
    ///
    /// No memory is freed — OS pages stay mapped and TLB-warm. If
    /// `drop-tracking` is enabled, all registered destructors run first.
    ///
    /// Complexity is O(`peak_blocks`) — only blocks that were actually used
    /// since the last reset are zeroed. Single-block arenas pay O(1).
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// for _ in 0..100 { let _ = arena.alloc(0u64); }
    /// arena.reset();
    /// assert_eq!(arena.stats().bytes_allocated, 0);
    /// ```
    pub fn reset(&mut self) {
        #[cfg(feature = "drop-tracking")]
        self.drop_registry.run_all_drops();
        for i in 0..=self.high_water_mark {
            self.blocks.get_mut(i).offset = 0;
        }
        self.high_water_mark = 0;
        self.bytes_allocated = 0;
        // Set block 0 directly without recomputing largest_remaining via set_current_block
        let b0 = self.blocks.get(0);
        self.current = 0;
        self.cur_base = b0.base;
        self.cur_ptr = b0.base;
        self.cur_end = unsafe { b0.base.add(b0.capacity) };
        // largest_remaining = max capacity among retained blocks (compute once)
        self.largest_remaining = if self.blocks.len() > 1 {
            let mut max_rem = 0;
            let mut max_idx = 0;
            for i in 1..self.blocks.len() {
                let cap = self.blocks.get(i).capacity;
                if cap > max_rem {
                    max_rem = cap;
                    max_idx = i;
                }
            }
            self.largest_remaining_idx = max_idx;
            max_rem
        } else {
            self.largest_remaining_idx = 0;
            0
        };
    }
}

impl Arena {
    /// Open a [`Transaction`] on this arena.
    ///
    /// All allocations made through the guard are rolled back automatically
    /// when it is dropped, unless [`Transaction::commit`] is called first.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let mut txn = arena.transaction();
    /// txn.alloc(1u32);
    /// txn.alloc(2u32);
    /// txn.commit();
    /// assert!(arena.stats().bytes_allocated >= 8);
    /// ```
    #[inline]
    #[must_use = "dropping the Transaction immediately rolls back; bind it to a variable or call commit()"]
    pub fn transaction(&mut self) -> Transaction<'_> {
        Transaction::new(self)
    }

    /// Execute a closure inside a transaction.
    ///
    /// `Ok` commits; `Err` rolls back all allocations before returning.
    ///
    /// # Errors
    ///
    /// Returns the closure's error value after rolling back all allocations.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let result = arena.with_transaction(|txn| -> Result<u32, &str> {
    ///     let x = txn.alloc(21u32);
    ///     Ok(*x * 2)
    /// });
    /// assert_eq!(result, Ok(42));
    /// ```
    #[inline]
    pub fn with_transaction<F, T, E>(&mut self, f: F) -> Result<T, E>
    where
        F: FnOnce(&mut Transaction<'_>) -> Result<T, E>,
    {
        run_with_transaction(self, f)
    }

    /// Execute an infallible closure inside a transaction; always commits,
    /// even if the closure panics. The panic is re-raised after the commit.
    ///
    /// If you want rollback-on-panic, use [`Arena::with_transaction`] instead.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// let val = arena.with_transaction_infallible(|txn| {
    ///     *txn.alloc(7u32) * 6
    /// });
    /// assert_eq!(val, 42);
    /// ```
    #[inline]
    pub fn with_transaction_infallible<F, T>(&mut self, f: F) -> T
    where
        F: FnOnce(&mut Transaction<'_>) -> T,
    {
        run_with_transaction_infallible(self, f)
    }

    /// Current number of open transactions and savepoints.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// assert_eq!(arena.transaction_depth(), 0);
    /// {
    ///     let mut txn = arena.transaction();
    ///     assert_eq!(txn.depth(), 1);
    ///     txn.commit();
    /// }
    /// assert_eq!(arena.transaction_depth(), 0);
    /// ```
    #[inline]
    #[must_use]
    pub fn transaction_depth(&self) -> usize {
        self.txn_depth
    }
}

impl Arena {
    /// Register a raw pointer for destructor execution.
    ///
    /// Only available with the `drop-tracking` feature. Call this after
    /// [`Arena::alloc_uninit`] once the value is fully initialised.
    ///
    /// # Safety
    ///
    /// `ptr` must point to a fully initialised `T` allocated from this arena.
    /// Calling this twice for the same pointer causes a double-drop.
    #[cfg(feature = "drop-tracking")]
    pub unsafe fn register_drop<T>(&mut self, ptr: *mut T) {
        self.drop_registry.register(ptr);
    }

    /// # Safety
    ///
    /// This is a no-op when `drop-tracking` is disabled. No safety requirements
    /// apply since the function does nothing.
    #[cfg(not(feature = "drop-tracking"))]
    pub unsafe fn register_drop<T>(&mut self, _ptr: *mut T) {}

    /// Register `count` contiguous elements starting at `ptr` for destructor
    /// execution. O(1) — adds a single slice entry to the registry.
    ///
    /// Only available with the `drop-tracking` feature. Use this after
    /// [`Arena::alloc_slice_uninit`] once all elements are fully initialised,
    /// or to hand off ownership of an `ArenaVec` slice via
    /// [`crate::ArenaVec::finish`] (which calls this internally).
    ///
    /// # Safety
    ///
    /// - `ptr` must point to a contiguous run of `count` fully initialised
    ///   `T` values, all allocated from this arena.
    /// - The same range must not have been registered before — duplicate
    ///   registration causes a double-drop on reset/rewind.
    #[cfg(feature = "drop-tracking")]
    pub unsafe fn register_drop_slice<T>(&mut self, ptr: *mut T, count: usize) {
        self.drop_registry.register_slice(ptr, count);
    }

    /// # Safety
    ///
    /// No-op when `drop-tracking` is disabled. No safety requirements apply.
    #[cfg(not(feature = "drop-tracking"))]
    pub unsafe fn register_drop_slice<T>(&mut self, _ptr: *mut T, _count: usize) {}

    /// Return a point-in-time snapshot of memory usage. O(1).
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::new();
    /// for _ in 0..100 { let _ = arena.alloc(0u64); }
    /// let stats = arena.stats();
    /// assert!(stats.bytes_allocated >= 800);
    /// println!("{:.1}% utilized", stats.utilization() * 100.0);
    /// ```
    #[inline(always)]
    pub fn stats(&self) -> ArenaStats {
        let current_used = self.cur_ptr as usize - self.cur_base as usize;
        ArenaStats {
            bytes_allocated: self.bytes_allocated + current_used,
            bytes_reserved: self.bytes_reserved,
            block_count: self.blocks.len(),
        }
    }

    /// Number of blocks currently owned by the arena.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastarena::Arena;
    ///
    /// let mut arena = Arena::with_capacity(64);
    /// for _ in 0..100 { let _ = arena.alloc(0u64); }
    /// assert!(arena.block_count() > 1);
    /// ```
    #[inline(always)]
    #[must_use]
    pub fn block_count(&self) -> usize {
        self.blocks.len()
    }
}

impl Arena {
    /// Write elements from an iterator into an arena-allocated buffer.
    ///
    /// Writes directly to destination. For Copy types with bulk data,
    /// use alloc_slice_copy (single memcpy) instead.
    #[inline(always)]
    unsafe fn write_slice_bulk<T, I: Iterator<Item = T>>(
        dst: *mut T,
        iter: &mut I,
        len: usize,
        _total_bytes: usize,
    ) {
        for i in 0..len {
            dst.add(i).write(iter.next().unwrap());
        }
    }

    /// Fast-path allocation: tries the current block, falls back to `alloc_slow`.
    ///
    /// Uses the same `align_up` address math as [`Block::try_alloc`](super::block::Block::try_alloc)
    /// instead of `align_offset`, which tends to codegen a little tighter on common targets.
    #[inline(always)]
    pub(crate) fn alloc_raw_inner(&mut self, size: usize, align: usize) -> NonNull<u8> {
        // For high-alignment requests, always use slow path to allocate a fresh block.
        if align > MIN_BLOCK_ALIGN {
            return self.alloc_slow(size, align);
        }
        let cur = self.cur_ptr as usize;
        let end = self.cur_end as usize;
        let aligned = align_up(cur, align);
        let Some(new_end) = aligned.checked_add(size) else {
            return self.alloc_slow(size, align);
        };
        if new_end <= end {
            let offset = aligned - cur;
            let aligned_ptr = unsafe { self.cur_ptr.add(offset) };
            self.cur_ptr = unsafe { aligned_ptr.add(size) };
            return unsafe { NonNull::new_unchecked(aligned_ptr) };
        }
        self.alloc_slow(size, align)
    }

    /// Fast-path fallible allocation: tries the current block, falls back to `alloc_slow_try`.
    #[inline(always)]
    pub(crate) fn try_alloc_raw_inner(&mut self, size: usize, align: usize) -> Option<NonNull<u8>> {
        // For high-alignment requests, always use slow path to allocate a fresh block.
        if align > MIN_BLOCK_ALIGN {
            return self.alloc_slow_try(size, align);
        }
        let cur = self.cur_ptr as usize;
        let end = self.cur_end as usize;
        let aligned = align_up(cur, align);
        let new_end = aligned.checked_add(size)?;
        if new_end <= end {
            let offset = aligned - cur;
            let aligned_ptr = unsafe { self.cur_ptr.add(offset) };
            self.cur_ptr = unsafe { aligned_ptr.add(size) };
            return Some(unsafe { NonNull::new_unchecked(aligned_ptr) });
        }
        self.alloc_slow_try(size, align)
    }

    /// Slow path: scans retained blocks for space, then allocates a new one.
    #[cold]
    fn alloc_slow(&mut self, size: usize, align: usize) -> NonNull<u8> {
        self.finish_slow_path(size, align);

        // For high-alignment requests, skip block scan entirely and allocate a new block.
        if align > MIN_BLOCK_ALIGN {
            return self.alloc_new_block(size, align);
        }

        // Skip block scan entirely when no retained block has enough free space.
        if size <= self.largest_remaining {
            for i in (self.current + 1)..self.blocks.len() {
                let block = self.blocks.get_mut(i);
                if block.align >= align {
                    if let Some((ptr, delta)) = block.try_alloc(size, align) {
                        self.bytes_allocated += delta;
                        self.set_current_block(i);
                        return ptr;
                    }
                }
            }
        }

        self.alloc_new_block(size, align)
    }

    /// Slow path (fallible): scans retained blocks for space, then tries to allocate a new one.
    #[cold]
    fn alloc_slow_try(&mut self, size: usize, align: usize) -> Option<NonNull<u8>> {
        self.finish_slow_path(size, align);

        // For high-alignment requests, skip block scan entirely and allocate a new block.
        if align > MIN_BLOCK_ALIGN {
            return self.try_alloc_new_block(size, align);
        }

        // Skip block scan entirely when no retained block has enough free space.
        if size <= self.largest_remaining {
            for i in (self.current + 1)..self.blocks.len() {
                let block = self.blocks.get_mut(i);
                if block.align >= align {
                    if let Some((ptr, delta)) = block.try_alloc(size, align) {
                        self.bytes_allocated += delta;
                        self.set_current_block(i);
                        return Some(ptr);
                    }
                }
            }
        }

        self.try_alloc_new_block(size, align)
    }

    /// Common slow-path setup: flushes the current block's state.
    #[inline]
    fn finish_slow_path(&mut self, _size: usize, _align: usize) {
        self.bytes_allocated += self.cur_ptr as usize - self.cur_base as usize;
        self.blocks.get_mut(self.current).offset = self.cur_ptr as usize - self.cur_base as usize;
    }

    /// Allocate a new block (infallible). Panics if allocation fails.
    #[inline]
    fn alloc_new_block(&mut self, size: usize, align: usize) -> NonNull<u8> {
        let block_size = self.next_block_for(size, align);
        let mut block = Block::new(block_size, align);
        let (ptr, delta) = block
            .try_alloc(size, align)
            .expect("fresh block must satisfy request");
        self.bytes_reserved += block_size;
        self.bytes_allocated += delta;
        self.blocks.push(block);
        self.set_current_block(self.blocks.len() - 1);
        ptr
    }

    /// Allocate a new block (fallible). Returns None if allocation fails.
    #[inline]
    fn try_alloc_new_block(&mut self, size: usize, align: usize) -> Option<NonNull<u8>> {
        let block_size = self.next_block_for(size, align);
        let mut block = Block::try_new(block_size, align)?;
        let (ptr, delta) = block.try_alloc(size, align)?;
        self.bytes_reserved += block_size;
        self.bytes_allocated += delta;
        self.blocks.push(block);
        self.set_current_block(self.blocks.len() - 1);
        Some(ptr)
    }

    /// Sets `idx` as the active block and updates cached pointers.
    #[inline(always)]
    fn set_current_block(&mut self, idx: usize) {
        let block = self.blocks.get(idx);
        self.current = idx;
        if idx > self.high_water_mark {
            self.high_water_mark = idx;
        }
        self.cur_base = block.base;
        self.cur_ptr = unsafe { block.base.add(block.offset) };
        self.cur_end = unsafe { block.base.add(block.capacity) };

        // Incremental update: if previous largest block is still valid, keep it
        let start = idx + 1;
        if self.largest_remaining_idx >= start {
            // Previous largest is still valid, just update its remaining
            let blk = self.blocks.get(self.largest_remaining_idx);
            self.largest_remaining = blk.capacity - blk.offset;
        } else {
            // Need to scan from start
            self.largest_remaining = self.compute_largest_remaining(idx);
        }
    }

    /// Computes the size of the next block.
    ///
    /// Uses 1.5x growth (`new = old * 3 / 2`) capped at [`MAX_BLOCK_SIZE`].
    /// Compared to 2x doubling, 1.5x growth wastes less arena memory while
    /// still being amortized O(1) per allocation.
    ///
    /// `next_block_size` itself grows by 1.5x on each call so successive
    /// blocks ramp up rapidly to absorb large workloads, then plateau at
    /// `MAX_BLOCK_SIZE`.
    fn next_block_for(&mut self, size: usize, align: usize) -> usize {
        let worst = size.saturating_add(align.saturating_sub(1));
        let mut candidate = self.next_block_size.max(worst).max(align * 2);

        // 1.5x growth: new = old * 3 / 2. The `.max(candidate + 1)` guards
        // against the (rare) case where `candidate < 2`, ensuring forward
        // progress even for tiny initial sizes.
        candidate = (candidate.saturating_mul(3) / 2)
            .max(candidate.saturating_add(1))
            .min(MAX_BLOCK_SIZE);

        // Update the cached "next size" hint so future block allocations
        // ramp up too.
        self.next_block_size = candidate.saturating_add(candidate / 2).min(MAX_BLOCK_SIZE);
        candidate
    }

    /// Computes the maximum contiguous free space in blocks after `from_idx`.
    /// Also updates largest_remaining_idx.
    #[inline]
    fn compute_largest_remaining(&mut self, from_idx: usize) -> usize {
        let mut max_rem = 0;
        let mut max_idx = from_idx;
        for i in (from_idx + 1)..self.blocks.len() {
            let rem = self.blocks.get(i).capacity - self.blocks.get(i).offset;
            if rem > max_rem {
                max_rem = rem;
                max_idx = i;
            }
        }
        self.largest_remaining_idx = max_idx;
        max_rem
    }
}