optirs-gpu 0.3.2

OptiRS GPU acceleration and multi-GPU optimization
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
// Arena allocator for GPU memory management
//
// This module implements arena (linear) allocators that allocate objects
// sequentially from a contiguous block of memory. Arena allocators are
// extremely fast for allocation and are ideal for temporary allocations
// that can be freed all at once.

use std::ptr::NonNull;
use std::sync::{Arc, Mutex};
use std::time::Instant;

/// Main arena allocator implementation
pub struct ArenaAllocator {
    /// Base pointer of the arena
    base_ptr: NonNull<u8>,
    /// Total size of the arena
    total_size: usize,
    /// Current allocation offset
    current_offset: usize,
    /// High water mark (maximum offset reached)
    high_water_mark: usize,
    /// Memory alignment requirement
    alignment: usize,
    /// Arena configuration
    config: ArenaConfig,
    /// Allocation tracking (if enabled)
    allocations: Vec<AllocationRecord>,
    /// Statistics
    stats: ArenaStats,
    /// Checkpoints for nested scopes
    checkpoints: Vec<ArenaCheckpoint>,
}

/// Arena allocation record
#[derive(Debug, Clone)]
pub struct AllocationRecord {
    /// Pointer to the allocation
    pub ptr: NonNull<u8>,
    /// Size of the allocation
    pub size: usize,
    /// Offset from base
    pub offset: usize,
    /// Timestamp of allocation
    pub allocated_at: Instant,
    /// Allocation ID for debugging
    pub id: u64,
    /// Optional debug tag
    pub tag: Option<String>,
}

/// Arena checkpoint for nested scopes
#[derive(Debug, Clone)]
pub struct ArenaCheckpoint {
    /// Offset at checkpoint creation
    pub offset: usize,
    /// Number of allocations at checkpoint
    pub allocation_count: usize,
    /// Timestamp of checkpoint creation
    pub created_at: Instant,
    /// Optional checkpoint name
    pub name: Option<String>,
}

/// Arena allocator configuration
#[derive(Debug, Clone)]
pub struct ArenaConfig {
    /// Memory alignment (must be power of 2)
    pub alignment: usize,
    /// Enable allocation tracking
    pub enable_tracking: bool,
    /// Enable debug mode with extra checks
    pub enable_debug: bool,
    /// Enable checkpoint support
    pub enable_checkpoints: bool,
    /// Enable statistics collection
    pub enable_stats: bool,
    /// Growth strategy for resizable arenas
    pub growth_strategy: GrowthStrategy,
    /// Initial capacity for allocation tracking
    pub initial_tracking_capacity: usize,
}

impl Default for ArenaConfig {
    fn default() -> Self {
        Self {
            alignment: 8,
            enable_tracking: false,
            enable_debug: false,
            enable_checkpoints: true,
            enable_stats: true,
            growth_strategy: GrowthStrategy::Fixed,
            initial_tracking_capacity: 1024,
        }
    }
}

/// Growth strategy for resizable arenas
///
/// Deliberately does not derive `PartialEq`: `Custom` carries a raw fn
/// pointer, and comparing fn pointers for equality is unreliable (their
/// addresses are not guaranteed unique across codegen units and identical
/// functions can be merged). Nothing in this crate compares two
/// `GrowthStrategy` values, so the honest fix is to not offer a comparison
/// that cannot mean what it appears to mean, rather than derive one anyway.
#[derive(Debug, Clone)]
pub enum GrowthStrategy {
    /// Fixed size arena (no growth)
    Fixed,
    /// Double the size when full
    Double,
    /// Linear growth by fixed amount
    Linear(usize),
    /// Custom growth function
    Custom(fn(usize) -> usize),
}

/// Arena allocator statistics
#[derive(Debug, Clone, Default)]
pub struct ArenaStats {
    /// Total number of allocations
    pub total_allocations: u64,
    /// Total bytes allocated
    pub total_bytes_allocated: u64,
    /// Current bytes allocated
    pub current_bytes_allocated: usize,
    /// Peak bytes allocated
    pub peak_bytes_allocated: usize,
    /// Number of resets
    pub reset_count: u64,
    /// Number of checkpoint operations
    pub checkpoint_count: u64,
    /// Number of rollback operations
    pub rollback_count: u64,
    /// Average allocation size
    pub average_allocation_size: f64,
    /// Allocation rate (allocations per second)
    pub allocation_rate: f64,
    /// Memory utilization ratio
    pub utilization_ratio: f64,
    /// Time of first allocation
    pub first_allocation_time: Option<Instant>,
    /// Time of last allocation
    pub last_allocation_time: Option<Instant>,
    /// Bytes skipped to satisfy a caller-requested alignment stricter than
    /// the arena's own (see [`ArenaAllocator::allocate_aligned`]) — real
    /// wasted space, not counted in `total_bytes_allocated`.
    pub bytes_wasted_to_alignment: u64,
}

impl ArenaStats {
    pub fn record_allocation(&mut self, size: usize) {
        let now = Instant::now();

        self.total_allocations += 1;
        self.total_bytes_allocated += size as u64;
        self.current_bytes_allocated += size;

        if self.current_bytes_allocated > self.peak_bytes_allocated {
            self.peak_bytes_allocated = self.current_bytes_allocated;
        }

        // Update average allocation size
        self.average_allocation_size =
            self.total_bytes_allocated as f64 / self.total_allocations as f64;

        // Update allocation rate
        if let Some(first_time) = self.first_allocation_time {
            let elapsed = now.duration_since(first_time).as_secs_f64();
            if elapsed > 0.0 {
                self.allocation_rate = self.total_allocations as f64 / elapsed;
            }
        } else {
            self.first_allocation_time = Some(now);
        }

        self.last_allocation_time = Some(now);
    }

    pub fn record_reset(&mut self) {
        self.reset_count += 1;
        self.current_bytes_allocated = 0;
    }

    pub fn record_checkpoint(&mut self) {
        self.checkpoint_count += 1;
    }

    pub fn record_rollback(&mut self, bytes_freed: usize) {
        self.rollback_count += 1;
        self.current_bytes_allocated = self.current_bytes_allocated.saturating_sub(bytes_freed);
    }

    pub fn update_utilization(&mut self, total_size: usize) {
        if total_size > 0 {
            self.utilization_ratio = self.current_bytes_allocated as f64 / total_size as f64;
        }
    }

    /// Record bytes skipped purely to satisfy an alignment requirement.
    pub fn record_padding(&mut self, padding: usize) {
        self.bytes_wasted_to_alignment += padding as u64;
    }
}

impl ArenaAllocator {
    /// Create a new arena allocator
    pub fn new(
        base_ptr: NonNull<u8>,
        size: usize,
        config: ArenaConfig,
    ) -> Result<Self, ArenaError> {
        if size == 0 {
            return Err(ArenaError::InvalidSize(
                "Arena size cannot be zero".to_string(),
            ));
        }

        if !config.alignment.is_power_of_two() {
            return Err(ArenaError::InvalidAlignment(format!(
                "Alignment {} is not a power of two",
                config.alignment
            )));
        }

        let allocations = if config.enable_tracking {
            Vec::with_capacity(config.initial_tracking_capacity)
        } else {
            Vec::new()
        };

        Ok(Self {
            base_ptr,
            total_size: size,
            current_offset: 0,
            high_water_mark: 0,
            alignment: config.alignment,
            allocations,
            stats: ArenaStats::default(),
            checkpoints: Vec::new(),
            config,
        })
    }

    /// Allocate memory from the arena
    pub fn allocate(&mut self, size: usize) -> Result<NonNull<u8>, ArenaError> {
        if size == 0 {
            return Err(ArenaError::InvalidSize(
                "Cannot allocate zero bytes".to_string(),
            ));
        }

        // Align the size
        let aligned_size = (size + self.alignment - 1) & !(self.alignment - 1);

        // Check if we have enough space
        if self.current_offset + aligned_size > self.total_size {
            return Err(ArenaError::OutOfMemory(format!(
                "Not enough space: need {}, have {}",
                aligned_size,
                self.total_size - self.current_offset
            )));
        }

        // Calculate the pointer
        let ptr =
            unsafe { NonNull::new_unchecked(self.base_ptr.as_ptr().add(self.current_offset)) };

        // Update state
        self.current_offset += aligned_size;
        if self.current_offset > self.high_water_mark {
            self.high_water_mark = self.current_offset;
        }

        // Record allocation
        if self.config.enable_tracking {
            let record = AllocationRecord {
                ptr,
                size: aligned_size,
                offset: self.current_offset - aligned_size,
                allocated_at: Instant::now(),
                id: self.stats.total_allocations,
                tag: None,
            };
            self.allocations.push(record);
        }

        // Update statistics
        if self.config.enable_stats {
            self.stats.record_allocation(aligned_size);
            self.stats.update_utilization(self.total_size);
        }

        Ok(ptr)
    }

    /// Allocate memory with a debug tag
    pub fn allocate_tagged(&mut self, size: usize, tag: String) -> Result<NonNull<u8>, ArenaError> {
        let ptr = self.allocate(size)?;

        if self.config.enable_tracking && !self.allocations.is_empty() {
            let last_idx = self.allocations.len() - 1;
            self.allocations[last_idx].tag = Some(tag);
        }

        Ok(ptr)
    }

    /// Allocate aligned memory
    pub fn allocate_aligned(
        &mut self,
        size: usize,
        alignment: usize,
    ) -> Result<NonNull<u8>, ArenaError> {
        if !alignment.is_power_of_two() {
            return Err(ArenaError::InvalidAlignment(format!(
                "Alignment {} is not a power of two",
                alignment
            )));
        }

        // Calculate aligned offset
        let aligned_offset = (self.current_offset + alignment - 1) & !(alignment - 1);
        let padding = aligned_offset - self.current_offset;

        // Check if we have enough space including padding
        if aligned_offset + size > self.total_size {
            return Err(ArenaError::OutOfMemory(format!(
                "Not enough space for aligned allocation: need {}, have {}",
                aligned_offset + size - self.current_offset,
                self.total_size - self.current_offset
            )));
        }

        // Update offset to aligned position
        self.current_offset = aligned_offset;
        if self.config.enable_stats && padding > 0 {
            self.stats.record_padding(padding);
        }

        // Now allocate normally
        self.allocate(size)
    }

    /// Reset the arena to empty state
    pub fn reset(&mut self) {
        self.current_offset = 0;

        if self.config.enable_tracking {
            self.allocations.clear();
        }

        if self.config.enable_stats {
            self.stats.record_reset();
            self.stats.update_utilization(self.total_size);
        }

        self.checkpoints.clear();
    }

    /// Create a checkpoint for later rollback
    pub fn checkpoint(&mut self) -> Result<CheckpointHandle, ArenaError> {
        if !self.config.enable_checkpoints {
            return Err(ArenaError::CheckpointsDisabled);
        }

        let checkpoint = ArenaCheckpoint {
            offset: self.current_offset,
            allocation_count: self.allocations.len(),
            created_at: Instant::now(),
            name: None,
        };

        self.checkpoints.push(checkpoint);

        if self.config.enable_stats {
            self.stats.record_checkpoint();
        }

        Ok(CheckpointHandle {
            index: self.checkpoints.len() - 1,
            offset: self.current_offset,
        })
    }

    /// Create a named checkpoint
    pub fn checkpoint_named(&mut self, name: String) -> Result<CheckpointHandle, ArenaError> {
        if !self.config.enable_checkpoints {
            return Err(ArenaError::CheckpointsDisabled);
        }

        let checkpoint = ArenaCheckpoint {
            offset: self.current_offset,
            allocation_count: self.allocations.len(),
            created_at: Instant::now(),
            name: Some(name),
        };

        self.checkpoints.push(checkpoint);

        if self.config.enable_stats {
            self.stats.record_checkpoint();
        }

        Ok(CheckpointHandle {
            index: self.checkpoints.len() - 1,
            offset: self.current_offset,
        })
    }

    /// Rollback to a checkpoint
    pub fn rollback(&mut self, handle: CheckpointHandle) -> Result<(), ArenaError> {
        if !self.config.enable_checkpoints {
            return Err(ArenaError::CheckpointsDisabled);
        }

        if handle.index >= self.checkpoints.len() {
            return Err(ArenaError::InvalidCheckpoint(
                "Checkpoint index out of range".to_string(),
            ));
        }

        let checkpoint = &self.checkpoints[handle.index];

        // A checkpoint's index can be reused by an unrelated, later checkpoint
        // once this same `rollback` truncates `self.checkpoints` past the
        // position it was originally recorded at (e.g. checkpoint A at index 0
        // is rolled back -- which truncates the vec to length 0 -- and then a
        // new checkpoint B is created and also lands at index 0). Trusting
        // `handle.index` alone would silently roll back to B's offset using a
        // handle the caller believes still refers to A, or underflow
        // `current_offset - checkpoint.offset` if B's offset happens to be
        // larger than the arena's current offset. Cross-check the offset
        // recorded in the handle at creation time against the checkpoint
        // currently stored at that index to detect and reject a stale handle.
        if checkpoint.offset != handle.offset {
            return Err(ArenaError::InvalidCheckpoint(
                "stale checkpoint handle: the checkpoint at this index was replaced since the handle was created".to_string(),
            ));
        }

        let bytes_freed = self.current_offset - checkpoint.offset;

        // Rollback state
        self.current_offset = checkpoint.offset;

        if self.config.enable_tracking {
            self.allocations.truncate(checkpoint.allocation_count);
        }

        // Remove checkpoints created after this one
        self.checkpoints.truncate(handle.index);

        if self.config.enable_stats {
            self.stats.record_rollback(bytes_freed);
            self.stats.update_utilization(self.total_size);
        }

        Ok(())
    }

    /// Get current usage information
    pub fn get_usage(&self) -> ArenaUsage {
        ArenaUsage {
            total_size: self.total_size,
            used_size: self.current_offset,
            free_size: self.total_size - self.current_offset,
            high_water_mark: self.high_water_mark,
            allocation_count: self.allocations.len(),
            checkpoint_count: self.checkpoints.len(),
            utilization_ratio: self.current_offset as f64 / self.total_size as f64,
        }
    }

    /// Get statistics
    pub fn get_stats(&self) -> &ArenaStats {
        &self.stats
    }

    /// Get allocation records (if tracking enabled)
    pub fn get_allocations(&self) -> &[AllocationRecord] {
        &self.allocations
    }

    /// Get checkpoints
    pub fn get_checkpoints(&self) -> &[ArenaCheckpoint] {
        &self.checkpoints
    }

    /// Check if a pointer belongs to this arena
    pub fn contains_pointer(&self, ptr: NonNull<u8>) -> bool {
        let ptr_addr = ptr.as_ptr() as usize;
        let base_addr = self.base_ptr.as_ptr() as usize;

        ptr_addr >= base_addr && ptr_addr < base_addr + self.current_offset
    }

    /// Get allocation info for a pointer (if tracking enabled)
    pub fn get_allocation_info(&self, ptr: NonNull<u8>) -> Option<&AllocationRecord> {
        if !self.config.enable_tracking {
            return None;
        }

        self.allocations.iter().find(|record| record.ptr == ptr)
    }

    /// Validate arena consistency
    pub fn validate(&self) -> Result<(), ArenaError> {
        if self.current_offset > self.total_size {
            return Err(ArenaError::CorruptedArena(format!(
                "Current offset {} exceeds total size {}",
                self.current_offset, self.total_size
            )));
        }

        if self.high_water_mark > self.total_size {
            return Err(ArenaError::CorruptedArena(format!(
                "High water mark {} exceeds total size {}",
                self.high_water_mark, self.total_size
            )));
        }

        if self.high_water_mark < self.current_offset {
            return Err(ArenaError::CorruptedArena(format!(
                "High water mark {} is less than current offset {}",
                self.high_water_mark, self.current_offset
            )));
        }

        // Validate tracking records if enabled
        if self.config.enable_tracking {
            let mut total_tracked_size = 0;

            for (i, record) in self.allocations.iter().enumerate() {
                // Check pointer is within arena bounds
                if !self.contains_pointer(record.ptr) {
                    return Err(ArenaError::CorruptedArena(format!(
                        "Allocation {} has pointer outside arena bounds",
                        i
                    )));
                }

                total_tracked_size += record.size;
            }

            // Note: total_tracked_size might be less than current_offset due to alignment padding
            if total_tracked_size > self.current_offset {
                return Err(ArenaError::CorruptedArena(format!(
                    "Tracked size {} exceeds current offset {}",
                    total_tracked_size, self.current_offset
                )));
            }
        }

        Ok(())
    }

    /// Get memory layout information
    pub fn get_memory_layout(&self) -> MemoryLayout {
        let mut layout = MemoryLayout {
            base_address: self.base_ptr.as_ptr() as usize,
            total_size: self.total_size,
            used_size: self.current_offset,
            regions: Vec::new(),
        };

        if self.config.enable_tracking {
            for record in &self.allocations {
                layout.regions.push(MemoryRegion {
                    offset: record.offset,
                    size: record.size,
                    allocated_at: record.allocated_at,
                    tag: record.tag.clone(),
                });
            }
        }

        layout
    }
}

// Safety: ArenaAllocator manages GPU memory pointers. While NonNull<u8> is not Send/Sync by default,
// it's safe to share ArenaAllocator across threads when protected by Arc<Mutex<>> because:
// 1. The pointers point to GPU memory managed by the GPU driver
// 2. The Mutex provides exclusive access for all mutable operations
// 3. No thread-local state is maintained
unsafe impl Send for ArenaAllocator {}
unsafe impl Sync for ArenaAllocator {}

/// Checkpoint handle for rollback operations
#[derive(Debug, Clone)]
pub struct CheckpointHandle {
    index: usize,
    offset: usize,
}

/// Arena usage information
#[derive(Debug, Clone)]
pub struct ArenaUsage {
    pub total_size: usize,
    pub used_size: usize,
    pub free_size: usize,
    pub high_water_mark: usize,
    pub allocation_count: usize,
    pub checkpoint_count: usize,
    pub utilization_ratio: f64,
}

/// Memory layout information
#[derive(Debug, Clone)]
pub struct MemoryLayout {
    pub base_address: usize,
    pub total_size: usize,
    pub used_size: usize,
    pub regions: Vec<MemoryRegion>,
}

/// Memory region within arena
#[derive(Debug, Clone)]
pub struct MemoryRegion {
    pub offset: usize,
    pub size: usize,
    pub allocated_at: Instant,
    pub tag: Option<String>,
}

/// Ring buffer arena allocator for circular allocation patterns
pub struct RingArena {
    arena: ArenaAllocator,
    /// Read pointer for ring buffer
    read_offset: usize,
    /// Number of live allocations
    live_allocations: usize,
    /// Ring configuration
    ring_config: RingConfig,
}

/// Ring arena configuration
#[derive(Debug, Clone)]
pub struct RingConfig {
    /// Enable overwrite protection
    pub overwrite_protection: bool,
    /// Callback when data is overwritten
    pub overwrite_callback: Option<fn(*mut u8, usize)>,
    /// Enable statistics
    pub enable_stats: bool,
}

impl Default for RingConfig {
    fn default() -> Self {
        Self {
            overwrite_protection: true,
            overwrite_callback: None,
            enable_stats: true,
        }
    }
}

impl RingArena {
    pub fn new(
        base_ptr: NonNull<u8>,
        size: usize,
        ring_config: RingConfig,
    ) -> Result<Self, ArenaError> {
        let arena_config = ArenaConfig {
            enable_tracking: ring_config.enable_stats,
            enable_checkpoints: false,
            ..ArenaConfig::default()
        };

        let arena = ArenaAllocator::new(base_ptr, size, arena_config)?;

        Ok(Self {
            arena,
            read_offset: 0,
            live_allocations: 0,
            ring_config,
        })
    }

    /// Allocate from ring buffer
    pub fn allocate(&mut self, size: usize) -> Result<NonNull<u8>, ArenaError> {
        // Check if allocation would wrap around and collide with live data
        if self.ring_config.overwrite_protection {
            let aligned_size = (size + self.arena.alignment - 1) & !(self.arena.alignment - 1);

            if self.arena.current_offset + aligned_size > self.arena.total_size {
                // Would wrap around
                if self.read_offset > 0 && aligned_size > self.read_offset {
                    return Err(ArenaError::RingBufferFull(
                        "Ring buffer full, would overwrite live data".to_string(),
                    ));
                }

                // Safe to wrap
                self.arena.current_offset = 0;
            } else if self.read_offset > self.arena.current_offset {
                // Normal case, check collision
                if self.arena.current_offset + aligned_size > self.read_offset {
                    return Err(ArenaError::RingBufferFull(
                        "Ring buffer full, would overwrite live data".to_string(),
                    ));
                }
            }
        }

        let ptr = self.arena.allocate(size)?;
        self.live_allocations += 1;

        Ok(ptr)
    }

    /// Mark data as consumed (advance read pointer)
    pub fn consume(&mut self, size: usize) -> Result<(), ArenaError> {
        let aligned_size = (size + self.arena.alignment - 1) & !(self.arena.alignment - 1);

        if self.read_offset + aligned_size > self.arena.total_size {
            // Wrap around
            self.read_offset = aligned_size - (self.arena.total_size - self.read_offset);
        } else {
            self.read_offset += aligned_size;
        }

        self.live_allocations = self.live_allocations.saturating_sub(1);

        Ok(())
    }

    /// Reset ring buffer
    pub fn reset(&mut self) {
        self.arena.reset();
        self.read_offset = 0;
        self.live_allocations = 0;
    }

    /// Get ring buffer usage
    pub fn get_ring_usage(&self) -> RingUsage {
        let total_size = self.arena.total_size;
        let write_offset = self.arena.current_offset;

        let used_size = if write_offset >= self.read_offset {
            write_offset - self.read_offset
        } else {
            total_size - self.read_offset + write_offset
        };

        RingUsage {
            total_size,
            used_size,
            free_size: total_size - used_size,
            read_offset: self.read_offset,
            write_offset,
            live_allocations: self.live_allocations,
        }
    }
}

/// Ring buffer usage information
#[derive(Debug, Clone)]
pub struct RingUsage {
    pub total_size: usize,
    pub used_size: usize,
    pub free_size: usize,
    pub read_offset: usize,
    pub write_offset: usize,
    pub live_allocations: usize,
}

/// Growing arena that can expand its capacity
pub struct GrowingArena {
    /// Current arena
    current_arena: ArenaAllocator,
    /// Previous arenas (for lookups)
    previous_arenas: Vec<ArenaAllocator>,
    /// Growth strategy
    growth_strategy: GrowthStrategy,
    /// External memory allocator for growth
    external_allocator: Option<Box<dyn ExternalAllocator>>,
}

/// External allocator trait for growing arenas
pub trait ExternalAllocator {
    fn allocate(&mut self, size: usize) -> Result<NonNull<u8>, ArenaError>;
    fn deallocate(&mut self, ptr: NonNull<u8>, size: usize);
}

impl GrowingArena {
    pub fn new(
        base_ptr: NonNull<u8>,
        initial_size: usize,
        growth_strategy: GrowthStrategy,
    ) -> Result<Self, ArenaError> {
        let config = ArenaConfig::default();
        let arena = ArenaAllocator::new(base_ptr, initial_size, config)?;

        Ok(Self {
            current_arena: arena,
            previous_arenas: Vec::new(),
            growth_strategy,
            external_allocator: None,
        })
    }

    pub fn with_external_allocator(mut self, allocator: Box<dyn ExternalAllocator>) -> Self {
        self.external_allocator = Some(allocator);
        self
    }

    /// Allocate with automatic growth
    pub fn allocate(&mut self, size: usize) -> Result<NonNull<u8>, ArenaError> {
        // Try current arena first
        match self.current_arena.allocate(size) {
            Ok(ptr) => Ok(ptr),
            Err(ArenaError::OutOfMemory(_)) => {
                // Need to grow
                self.grow(size)?;
                self.current_arena.allocate(size)
            }
            Err(e) => Err(e),
        }
    }

    fn grow(&mut self, min_additional_size: usize) -> Result<(), ArenaError> {
        if self.external_allocator.is_none() {
            return Err(ArenaError::CannotGrow(
                "No external allocator configured".to_string(),
            ));
        }

        let current_size = self.current_arena.total_size;
        let new_size = match &self.growth_strategy {
            GrowthStrategy::Fixed => {
                return Err(ArenaError::CannotGrow("Fixed size arena".to_string()))
            }
            GrowthStrategy::Double => current_size * 2,
            GrowthStrategy::Linear(increment) => current_size + increment,
            GrowthStrategy::Custom(func) => func(current_size),
        };

        let actual_new_size = new_size.max(min_additional_size);

        let new_ptr = self
            .external_allocator
            .as_mut()
            .ok_or_else(|| ArenaError::CannotGrow("No external allocator configured".to_string()))?
            .allocate(actual_new_size)?;

        // Move current arena to previous arenas
        let old_arena = std::mem::replace(
            &mut self.current_arena,
            ArenaAllocator::new(new_ptr, actual_new_size, ArenaConfig::default())?,
        );

        self.previous_arenas.push(old_arena);

        Ok(())
    }

    /// Check if pointer belongs to any arena
    pub fn contains_pointer(&self, ptr: NonNull<u8>) -> bool {
        if self.current_arena.contains_pointer(ptr) {
            return true;
        }

        self.previous_arenas
            .iter()
            .any(|arena| arena.contains_pointer(ptr))
    }

    /// Get total usage across all arenas
    pub fn get_total_usage(&self) -> GrowingArenaUsage {
        let mut total_size = self.current_arena.total_size;
        let mut used_size = self.current_arena.current_offset;
        let mut allocation_count = self.current_arena.allocations.len();

        for arena in &self.previous_arenas {
            total_size += arena.total_size;
            used_size += arena.current_offset;
            allocation_count += arena.allocations.len();
        }

        GrowingArenaUsage {
            total_size,
            used_size,
            free_size: total_size - used_size,
            arena_count: 1 + self.previous_arenas.len(),
            allocation_count,
            current_arena_size: self.current_arena.total_size,
            utilization_ratio: used_size as f64 / total_size as f64,
        }
    }
}

/// Growing arena usage information
#[derive(Debug, Clone)]
pub struct GrowingArenaUsage {
    pub total_size: usize,
    pub used_size: usize,
    pub free_size: usize,
    pub arena_count: usize,
    pub allocation_count: usize,
    pub current_arena_size: usize,
    pub utilization_ratio: f64,
}

/// Arena allocator errors
#[derive(Debug, Clone)]
pub enum ArenaError {
    InvalidSize(String),
    InvalidAlignment(String),
    OutOfMemory(String),
    CheckpointsDisabled,
    InvalidCheckpoint(String),
    CorruptedArena(String),
    RingBufferFull(String),
    CannotGrow(String),
}

impl std::fmt::Display for ArenaError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ArenaError::InvalidSize(msg) => write!(f, "Invalid size: {}", msg),
            ArenaError::InvalidAlignment(msg) => write!(f, "Invalid alignment: {}", msg),
            ArenaError::OutOfMemory(msg) => write!(f, "Out of memory: {}", msg),
            ArenaError::CheckpointsDisabled => write!(f, "Checkpoints are disabled"),
            ArenaError::InvalidCheckpoint(msg) => write!(f, "Invalid checkpoint: {}", msg),
            ArenaError::CorruptedArena(msg) => write!(f, "Corrupted arena: {}", msg),
            ArenaError::RingBufferFull(msg) => write!(f, "Ring buffer full: {}", msg),
            ArenaError::CannotGrow(msg) => write!(f, "Cannot grow: {}", msg),
        }
    }
}

impl std::error::Error for ArenaError {}

/// Thread-safe arena allocator wrapper
pub struct ThreadSafeArena {
    arena: Arc<Mutex<ArenaAllocator>>,
}

impl ThreadSafeArena {
    pub fn new(
        base_ptr: NonNull<u8>,
        size: usize,
        config: ArenaConfig,
    ) -> Result<Self, ArenaError> {
        let arena = ArenaAllocator::new(base_ptr, size, config)?;
        Ok(Self {
            arena: Arc::new(Mutex::new(arena)),
        })
    }

    pub fn allocate(&self, size: usize) -> Result<NonNull<u8>, ArenaError> {
        let mut arena = self.arena.lock().unwrap_or_else(|e| e.into_inner());
        arena.allocate(size)
    }

    pub fn reset(&self) {
        let mut arena = self.arena.lock().unwrap_or_else(|e| e.into_inner());
        arena.reset();
    }

    pub fn checkpoint(&self) -> Result<CheckpointHandle, ArenaError> {
        let mut arena = self.arena.lock().unwrap_or_else(|e| e.into_inner());
        arena.checkpoint()
    }

    pub fn rollback(&self, handle: CheckpointHandle) -> Result<(), ArenaError> {
        let mut arena = self.arena.lock().unwrap_or_else(|e| e.into_inner());
        arena.rollback(handle)
    }

    pub fn get_usage(&self) -> ArenaUsage {
        let arena = self.arena.lock().unwrap_or_else(|e| e.into_inner());
        arena.get_usage()
    }

    pub fn get_stats(&self) -> ArenaStats {
        let arena = self.arena.lock().unwrap_or_else(|e| e.into_inner());
        arena.get_stats().clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_arena_creation() {
        let size = 4096;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = ArenaConfig::default();
        let arena = ArenaAllocator::new(ptr, size, config);
        assert!(arena.is_ok());
    }

    #[test]
    fn test_basic_allocation() {
        let size = 4096;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = ArenaConfig::default();
        let mut arena = ArenaAllocator::new(ptr, size, config).expect("unwrap failed");

        let alloc1 = arena.allocate(100);
        assert!(alloc1.is_ok());

        let alloc2 = arena.allocate(200);
        assert!(alloc2.is_ok());

        let usage = arena.get_usage();
        assert!(usage.used_size > 0);
        assert!(usage.allocation_count == 2 || !arena.config.enable_tracking);
    }

    #[test]
    fn test_alignment() {
        let size = 4096;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = ArenaConfig {
            alignment: 16,
            ..ArenaConfig::default()
        };
        let mut arena = ArenaAllocator::new(ptr, size, config).expect("unwrap failed");

        let alloc_ptr = arena.allocate(10).expect("unwrap failed");
        assert_eq!(alloc_ptr.as_ptr() as usize % 16, 0);
    }

    #[test]
    fn test_allocate_aligned_records_padding_in_stats() {
        let size = 4096;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = ArenaConfig {
            alignment: 1,
            ..ArenaConfig::default()
        };
        let mut arena = ArenaAllocator::new(ptr, size, config).expect("unwrap failed");
        assert_eq!(arena.get_stats().bytes_wasted_to_alignment, 0);

        // With `alignment: 1` this lands the offset at exactly 3 (no
        // rounding), off of any larger power-of-two boundary.
        arena.allocate(3).expect("unwrap failed");

        // Aligning to 64 from offset 3 must skip 61 real bytes (3 -> 64).
        arena
            .allocate_aligned(10, 64)
            .expect("aligned allocation should succeed");
        assert_eq!(arena.get_stats().bytes_wasted_to_alignment, 61);

        // A second aligned allocation that needs no padding (offset is
        // already 64-aligned after the first one landed exactly on 64+10's
        // own alignment) must not inflate the counter further than reality.
        let before = arena.get_stats().bytes_wasted_to_alignment;
        arena
            .allocate_aligned(4, 1)
            .expect("aligned allocation should succeed");
        assert_eq!(arena.get_stats().bytes_wasted_to_alignment, before);
    }

    #[test]
    fn test_checkpoints() {
        let size = 4096;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = ArenaConfig {
            enable_checkpoints: true,
            enable_tracking: true,
            ..ArenaConfig::default()
        };
        let mut arena = ArenaAllocator::new(ptr, size, config).expect("unwrap failed");

        arena.allocate(100).expect("unwrap failed");
        let checkpoint = arena.checkpoint().expect("unwrap failed");
        arena.allocate(200).expect("unwrap failed");

        let usage_before = arena.get_usage();
        arena.rollback(checkpoint).expect("unwrap failed");
        let usage_after = arena.get_usage();

        assert!(usage_after.used_size < usage_before.used_size);
    }

    #[test]
    fn test_rollback_rejects_stale_handle_after_index_reuse() {
        let size = 4096;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = ArenaConfig {
            enable_checkpoints: true,
            enable_tracking: true,
            ..ArenaConfig::default()
        };
        let mut arena = ArenaAllocator::new(ptr, size, config).expect("unwrap failed");

        arena.allocate(100).expect("unwrap failed");
        let handle_a = arena.checkpoint().expect("unwrap failed");

        // Rolling back to A truncates `checkpoints` back to empty, freeing
        // index 0 for reuse by an unrelated, later checkpoint.
        arena.rollback(handle_a.clone()).expect("unwrap failed");

        // A brand new checkpoint B now lands at the same index 0 that A used
        // to occupy, but at a different offset.
        arena.allocate(50).expect("unwrap failed");
        arena.checkpoint().expect("unwrap failed");

        // Reusing the now-stale `handle_a` (same index, stale recorded
        // offset) must be rejected rather than silently rolling back to B's
        // position under A's name.
        let result = arena.rollback(handle_a);
        assert!(matches!(result, Err(ArenaError::InvalidCheckpoint(_))));
    }

    #[test]
    fn test_reset() {
        let size = 4096;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = ArenaConfig::default();
        let mut arena = ArenaAllocator::new(ptr, size, config).expect("unwrap failed");

        arena.allocate(100).expect("unwrap failed");
        arena.allocate(200).expect("unwrap failed");

        let usage_before = arena.get_usage();
        assert!(usage_before.used_size > 0);

        arena.reset();
        let usage_after = arena.get_usage();
        assert_eq!(usage_after.used_size, 0);
    }

    #[test]
    fn test_ring_arena() {
        let size = 1024;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = RingConfig::default();
        let mut ring = RingArena::new(ptr, size, config).expect("unwrap failed");

        let alloc1 = ring.allocate(100);
        assert!(alloc1.is_ok());

        ring.consume(100).expect("unwrap failed");

        let alloc2 = ring.allocate(100);
        assert!(alloc2.is_ok());
    }

    #[test]
    fn test_thread_safe_arena() {
        let size = 4096;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = ArenaConfig::default();
        let arena = ThreadSafeArena::new(ptr, size, config).expect("unwrap failed");

        let alloc_result = arena.allocate(100);
        assert!(alloc_result.is_ok());

        let usage = arena.get_usage();
        assert!(usage.used_size > 0);
    }

    #[test]
    fn test_arena_validation() {
        let size = 4096;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = ArenaConfig {
            enable_tracking: true,
            ..ArenaConfig::default()
        };
        let mut arena = ArenaAllocator::new(ptr, size, config).expect("unwrap failed");

        arena.allocate(100).expect("unwrap failed");
        arena.allocate(200).expect("unwrap failed");

        let validation_result = arena.validate();
        assert!(validation_result.is_ok());
    }
}