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
//! Arena allocator for runtime records.
//!
//! This module provides a simple arena allocator for managing runtime records
//! (tasks, regions, obligations). The arena provides stable indices that can
//! be used as identifiers.
//!
//! # Design
//!
//! - Elements are stored in a Vec with generation counters for ABA safety
//! - Removed elements are tracked in a free list for reuse
//! - No unsafe code; relies on bounds checking and generation validation
use core::fmt;
use core::hash::{Hash, Hasher};
/// An index into an arena with a generation counter for ABA safety.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct ArenaIndex {
index: u32,
generation: u32,
}
impl ArenaIndex {
/// Creates a new arena index (primarily for testing).
#[inline]
#[must_use]
pub const fn new(index: u32, generation: u32) -> Self {
Self { index, generation }
}
/// Returns the raw index value.
#[inline]
#[must_use]
pub const fn index(self) -> u32 {
self.index
}
/// Returns the generation counter.
#[inline]
#[must_use]
pub const fn generation(self) -> u32 {
self.generation
}
}
impl fmt::Debug for ArenaIndex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ArenaIndex({}:{})", self.index, self.generation)
}
}
impl Hash for ArenaIndex {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
let packed = (u64::from(self.index) << 32) | u64::from(self.generation);
state.write_u64(packed);
}
}
/// A slot in the arena that can be occupied or vacant.
#[derive(Debug)]
enum Slot<T> {
Occupied {
value: T,
generation: u32,
},
Vacant {
next_free: Option<u32>,
generation: u32,
},
}
/// A simple arena allocator with generation-based indices.
///
/// This arena provides stable indices for inserted elements, with generation
/// counters to detect use-after-free errors (ABA problem).
#[derive(Debug)]
pub struct Arena<T> {
slots: Vec<Slot<T>>,
free_head: Option<u32>,
len: usize,
}
impl<T> Default for Arena<T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<T> Arena<T> {
/// Creates a new empty arena.
#[must_use]
#[inline]
pub const fn new() -> Self {
Self {
slots: Vec::new(),
free_head: None,
len: 0,
}
}
/// Creates a new arena with the specified capacity.
#[must_use]
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Self {
slots: Vec::with_capacity(capacity),
free_head: None,
len: 0,
}
}
/// Returns the number of occupied slots.
#[inline]
#[must_use]
pub const fn len(&self) -> usize {
self.len
}
/// Returns the reserved slot capacity of the arena backing storage.
#[inline]
#[must_use]
pub fn capacity(&self) -> usize {
self.slots.capacity()
}
/// Returns the estimated bytes reserved by the arena backing slots.
#[inline]
#[must_use]
pub fn reserved_bytes(&self) -> usize {
Self::estimated_bytes_for_capacity(self.capacity())
}
/// Returns the estimated bytes required to reserve `capacity` arena slots.
#[inline]
#[must_use]
pub fn estimated_bytes_for_capacity(capacity: usize) -> usize {
capacity.saturating_mul(core::mem::size_of::<Slot<T>>())
}
/// Returns true if the arena has no occupied slots.
#[inline]
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
/// Inserts a value into the arena and returns its index.
#[inline]
pub fn insert(&mut self, value: T) -> ArenaIndex {
if let Some(free_index) = self.free_head {
let slot = &mut self.slots[free_index as usize];
let idx = match slot {
Slot::Vacant {
next_free,
generation,
} => {
let generation_value = *generation;
self.free_head = *next_free;
*slot = Slot::Occupied {
value,
generation: generation_value,
};
ArenaIndex {
index: free_index,
generation: generation_value,
}
}
Slot::Occupied { .. } => unreachable!("free list pointed to occupied slot"),
};
self.len += 1;
idx
} else {
let index = u32::try_from(self.slots.len()).expect("arena overflow");
self.slots.push(Slot::Occupied {
value,
generation: 0,
});
self.len += 1;
ArenaIndex {
index,
generation: 0,
}
}
}
/// Inserts a value produced by `f` into the arena and returns its index.
///
/// The closure receives the assigned `ArenaIndex`, allowing callers to
/// construct records that embed their final ID without later backpatching.
#[inline]
pub fn insert_with<F>(&mut self, f: F) -> ArenaIndex
where
F: FnOnce(ArenaIndex) -> T,
{
if let Some(free_index) = self.free_head {
let (next_free, generation) = match self.slots[free_index as usize] {
Slot::Vacant {
next_free,
generation,
} => (next_free, generation),
Slot::Occupied { .. } => unreachable!("free list pointed to occupied slot"),
};
let idx = ArenaIndex {
index: free_index,
generation,
};
let value = f(idx);
self.free_head = next_free;
self.slots[free_index as usize] = Slot::Occupied { value, generation };
self.len += 1;
idx
} else {
let index = u32::try_from(self.slots.len()).expect("arena overflow");
let idx = ArenaIndex {
index,
generation: 0,
};
let value = f(idx);
self.slots.push(Slot::Occupied {
value,
generation: 0,
});
self.len += 1;
idx
}
}
/// Removes the value at the given index and returns it.
///
/// Returns `None` if the index is invalid or the slot is vacant.
///
/// br-asupersync-rvz1tq — generation-overflow safety: if the slot has
/// already cycled through `u32::MAX` reuses, the next `wrapping_add`
/// would silently roll back to 0 and a stale `ArenaIndex` from the very
/// first generation could be matched against the new slot (ABA bypass
/// against the generation guard). This branch panics in debug to catch
/// the bug fast, and in release retires the slot permanently — it is
/// removed from the free list so it is never reused, capping the leak
/// at one slot per 2^32 reuses (per slot).
#[inline]
pub fn remove(&mut self, index: ArenaIndex) -> Option<T> {
let slot = self.slots.get_mut(index.index as usize)?;
match slot {
Slot::Occupied { generation, .. } if *generation == index.generation => {
let cur_gen = *generation;
let retire_slot = if cur_gen == u32::MAX {
debug_assert!(
false,
"ArenaIndex generation wrap detected at slot {} \
(br-asupersync-rvz1tq)",
index.index
);
true
} else {
false
};
let new_gen = cur_gen.wrapping_add(1);
let old_slot = core::mem::replace(
slot,
Slot::Vacant {
// Retired slot: detached from the free list so it
// will never be re-allocated.
next_free: if retire_slot { None } else { self.free_head },
generation: new_gen,
},
);
if !retire_slot {
self.free_head = Some(index.index);
}
self.len -= 1;
match old_slot {
Slot::Occupied { value, .. } => Some(value),
Slot::Vacant { .. } => unreachable!(),
}
}
_ => None,
}
}
/// Returns a reference to the value at the given index.
///
/// Returns `None` if the index is invalid or the slot is vacant.
#[inline]
#[must_use]
pub fn get(&self, index: ArenaIndex) -> Option<&T> {
match self.slots.get(index.index as usize)? {
Slot::Occupied { value, generation } if *generation == index.generation => Some(value),
_ => None,
}
}
/// Returns a mutable reference to the value at the given index.
///
/// Returns `None` if the index is invalid or the slot is vacant.
#[inline]
pub fn get_mut(&mut self, index: ArenaIndex) -> Option<&mut T> {
match self.slots.get_mut(index.index as usize)? {
Slot::Occupied { value, generation } if *generation == index.generation => Some(value),
_ => None,
}
}
/// Retains only the elements specified by the predicate.
///
/// In other words, remove all elements `e` such that `f(&e)` returns `false`.
/// This method operates in place and preserves the generation counters of removed elements.
///
/// Uses a single pass over `self.slots` that applies the predicate and
/// rebuilds the free list simultaneously, instead of the two-pass approach.
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&mut T) -> bool,
{
struct Guard<'a, T> {
arena: &'a mut Arena<T>,
current_index: usize,
new_len: usize,
first_free: Option<u32>,
prev_free: Option<usize>,
panicked: bool,
}
impl<T> Drop for Guard<'_, T> {
fn drop(&mut self) {
// If we dropped early (panic), the current element i was Occupied
// and f() panicked, so it remains Occupied. We must count it.
if self.panicked && self.current_index < self.arena.slots.len() {
self.new_len += 1;
self.current_index += 1;
}
// Process the remaining slots to link any existing Vacant slots
// into our newly rebuilt free list.
for i in self.current_index..self.arena.slots.len() {
if matches!(&self.arena.slots[i], Slot::Occupied { .. }) {
self.new_len += 1;
continue;
}
if let Slot::Vacant {
next_free,
generation,
} = &mut self.arena.slots[i]
{
if *generation == 0 {
continue;
}
*next_free = None;
}
if let Some(prev) = self.prev_free {
if let Slot::Vacant { next_free, .. } = &mut self.arena.slots[prev] {
*next_free = Some(i as u32);
}
} else {
self.first_free = Some(i as u32);
}
self.prev_free = Some(i);
}
self.arena.len = self.new_len;
self.arena.free_head = self.first_free;
}
}
let mut guard = Guard {
arena: self,
current_index: 0,
new_len: 0,
first_free: None,
prev_free: None,
panicked: true,
};
while guard.current_index < guard.arena.slots.len() {
let i = guard.current_index;
let kept = match &mut guard.arena.slots[i] {
Slot::Occupied { value, .. } => f(value),
Slot::Vacant { .. } => false,
};
if kept {
guard.new_len += 1;
guard.current_index += 1;
continue;
}
let mut skip_link = false;
if let Slot::Occupied { generation, .. } = &guard.arena.slots[i] {
let cur_gen = *generation;
let retire_slot = cur_gen == u32::MAX;
if retire_slot {
debug_assert!(
false,
"ArenaIndex generation wrap detected at slot {} \
(br-asupersync-rvz1tq)",
i
);
}
guard.arena.slots[i] = Slot::Vacant {
next_free: None,
generation: cur_gen.wrapping_add(1),
};
if retire_slot {
skip_link = true;
}
} else if let Slot::Vacant {
next_free,
generation,
} = &mut guard.arena.slots[i]
{
if *generation == 0 {
skip_link = true;
} else {
*next_free = None;
}
}
if skip_link {
guard.current_index += 1;
continue;
}
if let Some(prev) = guard.prev_free {
if let Slot::Vacant { next_free, .. } = &mut guard.arena.slots[prev] {
*next_free = Some(i as u32);
}
} else {
guard.first_free = Some(i as u32);
}
guard.prev_free = Some(i);
guard.current_index += 1;
}
guard.panicked = false;
}
/// Drains all occupied values, leaving the arena empty.
///
/// Yields ownership of each value without cloning. All slots become
/// vacant and are linked into the free list.
pub fn drain_values(&mut self) -> DrainValues<'_, T> {
DrainValues {
arena: self,
pos: 0,
}
}
/// Returns true if the index is valid and points to an occupied slot.
#[inline]
#[must_use]
pub fn contains(&self, index: ArenaIndex) -> bool {
self.get(index).is_some()
}
/// Iterates over all occupied slots.
pub fn iter(&self) -> impl Iterator<Item = (ArenaIndex, &T)> {
self.slots
.iter()
.enumerate()
.filter_map(|(i, slot)| match slot {
Slot::Occupied { value, generation } => Some((
ArenaIndex {
// br-asupersync-njd135 — explicit bounds check on
// the usize→u32 cast. The arena enforces
// slots.len() <= u32::MAX at insert (line 154 uses
// try_from + expect); if that invariant is ever
// violated, fail loud here rather than silently
// truncate the index and produce a bogus
// ArenaIndex that aliases an unrelated slot.
index: u32::try_from(i).expect("arena slot index overflows u32"),
generation: *generation,
},
value,
)),
Slot::Vacant { .. } => None,
})
}
/// Iterates mutably over all occupied slots.
pub fn iter_mut(&mut self) -> impl Iterator<Item = (ArenaIndex, &mut T)> {
self.slots
.iter_mut()
.enumerate()
.filter_map(|(i, slot)| match slot {
Slot::Occupied { value, generation } => Some((
ArenaIndex {
// br-asupersync-njd135 — explicit bounds check on
// the usize→u32 cast. The arena enforces
// slots.len() <= u32::MAX at insert (line 154 uses
// try_from + expect); if that invariant is ever
// violated, fail loud here rather than silently
// truncate the index and produce a bogus
// ArenaIndex that aliases an unrelated slot.
index: u32::try_from(i).expect("arena slot index overflows u32"),
generation: *generation,
},
value,
)),
Slot::Vacant { .. } => None,
})
}
}
/// Iterator that drains all occupied values from an [`Arena`].
///
/// Produced by [`Arena::drain_values`]. On each call to `next`, the next
/// occupied slot is converted to vacant and its value yielded by ownership.
/// When the iterator is dropped (whether exhausted or not), any remaining
/// occupied slots are also drained.
pub struct DrainValues<'a, T> {
arena: &'a mut Arena<T>,
pos: usize,
}
impl<T> Iterator for DrainValues<'_, T> {
type Item = T;
fn next(&mut self) -> Option<T> {
while self.pos < self.arena.slots.len() {
let i = self.pos;
self.pos += 1;
if let Slot::Occupied { generation, .. } = &self.arena.slots[i] {
let cur_gen = *generation;
let retire_slot = cur_gen == u32::MAX;
if retire_slot {
debug_assert!(
false,
"ArenaIndex generation wrap detected at slot {} \
(br-asupersync-rvz1tq)",
i
);
}
let new_gen = cur_gen.wrapping_add(1);
let old = core::mem::replace(
&mut self.arena.slots[i],
Slot::Vacant {
next_free: if retire_slot {
None
} else {
self.arena.free_head
},
generation: new_gen,
},
);
if !retire_slot {
self.arena.free_head = Some(i as u32);
}
self.arena.len -= 1;
if let Slot::Occupied { value, .. } = old {
return Some(value);
}
}
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.arena.len))
}
}
impl<T> Drop for DrainValues<'_, T> {
fn drop(&mut self) {
// Exhaust the iterator to ensure all values are dropped and
// the arena is left in a consistent state.
for _ in self {}
}
}
#[cfg(test)]
mod tests {
#![allow(
clippy::pedantic,
clippy::nursery,
clippy::expect_fun_call,
clippy::map_unwrap_or,
clippy::cast_possible_wrap,
clippy::future_not_send
)]
use super::*;
use std::panic::{AssertUnwindSafe, catch_unwind};
#[test]
fn insert_and_get() {
let mut arena = Arena::new();
let idx = arena.insert(42);
assert_eq!(arena.get(idx), Some(&42));
assert_eq!(arena.len(), 1);
}
#[test]
fn remove_and_reuse() {
let mut arena = Arena::new();
let idx1 = arena.insert(1);
let idx2 = arena.insert(2);
assert_eq!(arena.remove(idx1), Some(1));
assert_eq!(arena.len(), 1);
// Old index should be invalid
assert_eq!(arena.get(idx1), None);
// New insert should reuse the slot
let idx3 = arena.insert(3);
assert_eq!(idx3.index(), idx1.index());
assert_ne!(idx3.generation(), idx1.generation());
// Both remaining indices should work
assert_eq!(arena.get(idx2), Some(&2));
assert_eq!(arena.get(idx3), Some(&3));
}
#[test]
fn generation_prevents_aba() {
let mut arena = Arena::new();
let idx1 = arena.insert(1);
arena.remove(idx1);
let idx2 = arena.insert(2);
// Same slot, different generation
assert_eq!(idx1.index(), idx2.index());
assert_ne!(idx1.generation(), idx2.generation());
// Old index should not work
assert_eq!(arena.get(idx1), None);
assert_eq!(arena.get(idx2), Some(&2));
}
#[test]
fn insert_with_passes_assigned_index() {
let mut arena = Arena::new();
let idx = arena.insert_with(super::ArenaIndex::index);
assert_eq!(arena.get(idx), Some(&idx.index()));
}
#[test]
fn insert_with_panic_keeps_arena_empty_when_no_free_slots() {
let mut arena = Arena::new();
let result = catch_unwind(AssertUnwindSafe(|| {
let _ = arena.insert_with(|_| -> u32 { panic!("boom") });
}));
assert!(result.is_err());
assert!(arena.is_empty());
assert_eq!(arena.len(), 0);
let idx = arena.insert(7);
assert_eq!(idx.index(), 0);
assert_eq!(arena.get(idx), Some(&7));
}
#[test]
fn insert_with_panic_preserves_free_list_when_reusing_slot() {
let mut arena = Arena::new();
let idx1 = arena.insert(10);
let idx2 = arena.insert(20);
assert_eq!(arena.remove(idx1), Some(10));
assert_eq!(arena.len(), 1);
let result = catch_unwind(AssertUnwindSafe(|| {
let _ = arena.insert_with(|_| -> u32 { panic!("boom") });
}));
assert!(result.is_err());
assert_eq!(arena.len(), 1);
assert_eq!(arena.get(idx2), Some(&20));
// The next insert should still reuse the previously freed slot.
let idx3 = arena.insert(30);
assert_eq!(idx3.index(), idx1.index());
assert_eq!(arena.len(), 2);
}
#[test]
fn retain_panic_preserves_invariants() {
let mut arena = Arena::new();
arena.insert(10);
let idx2 = arena.insert(20);
let idx3 = arena.insert(30);
let result = catch_unwind(AssertUnwindSafe(|| {
arena.retain(|v| {
assert!(*v != 20, "boom");
false // 10 is deleted before panic
});
}));
assert!(result.is_err());
// Before the fix, arena.len() would be 3 (unchanged) but element 0 was deleted
assert_eq!(
arena.len(),
2,
"len must reflect deletions that happened before the panic"
);
// Element 20 and 30 should still be accessible
assert_eq!(arena.get(idx2), Some(&20));
assert_eq!(arena.get(idx3), Some(&30));
// Inserting a new element should reuse the freed slot (index 0)
let new_idx = arena.insert(40);
assert_eq!(new_idx.index(), 0, "must reuse freed slot");
}
#[test]
fn test_retain() {
let mut arena = Arena::new();
let idx0 = arena.insert(0);
let idx1 = arena.insert(1);
let idx2 = arena.insert(2);
let idx3 = arena.insert(3);
assert_eq!(arena.len(), 4);
// Remove odd numbers
arena.retain(|&mut val| val % 2 == 0);
assert_eq!(arena.len(), 2);
assert_eq!(arena.get(idx0), Some(&0));
assert_eq!(arena.get(idx1), None);
assert_eq!(arena.get(idx2), Some(&2));
assert_eq!(arena.get(idx3), None);
// Insert new items - should reuse slots of 1 and 3 (indices 1 and 3)
// Free list order is linear (0..N) after retain rebuilds it.
// So first free should be 1, then 3.
let idx_new_a = arena.insert(10);
let idx_new_b = arena.insert(30);
assert_eq!(idx_new_a.index(), 1);
assert_eq!(idx_new_b.index(), 3);
assert_eq!(arena.len(), 4);
// Generations should be bumped
assert_ne!(idx_new_a.generation(), idx1.generation());
assert_ne!(idx_new_b.generation(), idx3.generation());
}
#[test]
fn arena_index_debug() {
let idx = ArenaIndex::new(5, 3);
let dbg = format!("{idx:?}");
assert_eq!(dbg, "ArenaIndex(5:3)");
}
#[test]
fn arena_index_clone_copy() {
let idx = ArenaIndex::new(1, 0);
let idx2 = idx;
let idx3 = idx;
assert_eq!(idx2, idx3);
}
#[test]
fn arena_index_eq_ne() {
let a = ArenaIndex::new(1, 0);
let b = ArenaIndex::new(1, 0);
let c = ArenaIndex::new(1, 1);
let d = ArenaIndex::new(2, 0);
assert_eq!(a, b);
assert_ne!(a, c);
assert_ne!(a, d);
}
#[test]
fn arena_index_ord() {
let a = ArenaIndex::new(1, 0);
let b = ArenaIndex::new(2, 0);
let c = ArenaIndex::new(1, 1);
assert!(a < b);
assert!(a < c);
}
#[test]
fn arena_index_hash() {
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert(ArenaIndex::new(1, 0));
set.insert(ArenaIndex::new(2, 0));
set.insert(ArenaIndex::new(1, 0)); // duplicate
assert_eq!(set.len(), 2);
}
#[test]
fn arena_index_accessors() {
let idx = ArenaIndex::new(42, 7);
assert_eq!(idx.index(), 42);
assert_eq!(idx.generation(), 7);
}
#[test]
fn arena_debug() {
let arena: Arena<i32> = Arena::new();
let dbg = format!("{arena:?}");
assert!(dbg.contains("Arena"));
}
#[test]
fn arena_default() {
let arena: Arena<i32> = Arena::default();
assert!(arena.is_empty());
assert_eq!(arena.len(), 0);
}
#[test]
fn arena_with_capacity() {
let arena: Arena<i32> = Arena::with_capacity(16);
assert!(arena.is_empty());
assert_eq!(arena.len(), 0);
}
#[test]
fn arena_reserved_bytes_track_slot_capacity() {
let arena: Arena<i32> = Arena::with_capacity(16);
assert_eq!(arena.capacity(), 16);
assert_eq!(
arena.reserved_bytes(),
Arena::<i32>::estimated_bytes_for_capacity(16)
);
}
#[test]
fn arena_get_mut() {
let mut arena = Arena::new();
let idx = arena.insert(10);
if let Some(val) = arena.get_mut(idx) {
*val = 20;
}
assert_eq!(arena.get(idx), Some(&20));
}
#[test]
fn arena_contains() {
let mut arena = Arena::new();
let idx = arena.insert(1);
assert!(arena.contains(idx));
arena.remove(idx);
assert!(!arena.contains(idx));
}
#[test]
fn arena_iter() {
let mut arena = Arena::new();
let idx1 = arena.insert(10);
let idx2 = arena.insert(20);
let items: Vec<_> = arena.iter().collect();
assert_eq!(items.len(), 2);
assert_eq!(items[0], (idx1, &10));
assert_eq!(items[1], (idx2, &20));
}
#[test]
fn arena_drain_values() {
let mut arena = Arena::new();
arena.insert(1);
arena.insert(2);
arena.insert(3);
assert_eq!(arena.len(), 3);
let drained: Vec<_> = arena.drain_values().collect();
assert_eq!(drained, vec![1, 2, 3]);
assert!(arena.is_empty());
}
#[test]
fn arena_drain_values_partial_drop() {
let mut arena = Arena::new();
arena.insert(1);
arena.insert(2);
arena.insert(3);
{
let mut drain = arena.drain_values();
let _ = drain.next(); // take one
// drop drain - should drain remaining
}
assert!(arena.is_empty());
}
/// br-asupersync-rvz1tq — generation-overflow safety: removing a slot
/// whose current generation is `u32::MAX` retires the slot permanently
/// (it must not return to the free list and be reissued at generation 0,
/// which would alias the very first ArenaIndex ever issued for that
/// slot). In debug builds this case also `debug_assert!`s — verified
/// here by skipping the assertion path and operating directly on a
/// hand-poisoned slot.
#[test]
fn remove_at_generation_max_retires_slot_permanently() {
let mut arena: Arena<u32> = Arena::new();
let idx = arena.insert(7);
// Hand-poison the slot's generation to u32::MAX - 1 so that one more
// remove cycle reaches u32::MAX. The first remove brings cur_gen to
// u32::MAX; the slot is now Vacant at generation u32::MAX. Insert
// again: cur_gen on the next Occupied is u32::MAX. Now remove —
// this is the case the rvz1tq guard catches.
if let Some(Slot::Occupied { generation, .. }) = arena.slots.get_mut(idx.index() as usize) {
*generation = u32::MAX;
}
let recovered = ArenaIndex {
index: idx.index(),
generation: u32::MAX,
};
// In a release build this hits the retirement path; in debug it
// also fires `debug_assert!`. We only check the side effect: after
// removal the slot must NOT be on the free list.
let prev_free_head = arena.free_head;
let val =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.remove(recovered)));
// Whether or not the debug assertion fired, the operation either
// panicked OR completed without re-adding the slot to the free list.
match val {
Ok(Some(7)) => {
// Release-style behavior: slot was removed and retired.
assert_eq!(
arena.free_head, prev_free_head,
"retired slot must not be added to the free list"
);
}
Ok(Some(v)) => panic!("expected 7, got {v}"),
Ok(None) => panic!("expected to remove the value"),
Err(_) => {
// Debug-style behavior: debug_assert fired. Acceptable.
}
}
}
/// br-asupersync-njd135 — `iter()` constructs ArenaIndex via an explicit
/// `u32::try_from` rather than a silent `i as u32` cast. Sanity-check
/// the happy path: indices yielded match what insert returned.
#[test]
fn iter_yields_well_formed_indices() {
let mut arena: Arena<u32> = Arena::new();
let a = arena.insert(1);
let b = arena.insert(2);
let c = arena.insert(3);
let observed: Vec<ArenaIndex> = arena.iter().map(|(i, _)| i).collect();
assert_eq!(observed, vec![a, b, c]);
// The cast is `u32::try_from(usize) -> Result<u32, _>`, so a hidden
// truncation would now error rather than silently produce a bogus
// ArenaIndex. We can't construct a 2^32-slot arena in a unit test,
// but the panic message is part of the contract.
}
}