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
//! Sparse stable pages, published once and reclaimed only under exclusive access.
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::marker::PhantomData;
use core::{mem, ptr, slice};
use super::atomic::{AtomicPtr, Ordering};
#[cfg(not(loom))]
const DIGIT: u32 = 6;
#[cfg(loom)]
const DIGIT: u32 = 2;
const FANOUT: usize = 1 << DIGIT;
const MASK: usize = FANOUT - 1;
// One root slot plus at most one branch per digit, including a partial digit.
const WALK_LEVELS: usize = usize::BITS.div_ceil(DIGIT) as usize + 1;
pub(crate) struct RadixSpine<P> {
root: AtomicPtr<()>,
owner: PhantomData<Box<P>>,
// The erased `AtomicPtr<()>` would leave P covariant, and `&self`
// inserts P: a `RadixSpine<&'static T>` could then be shortened to
// `RadixSpine<&'a T>`, store a short-lived reference, and later hand it
// out as `&'static T` (use after free). Spine is invariant through
// `AtomicPtr<AtomicPtr<P>>`; this marker restores the same here.
invariant: PhantomData<fn(P) -> P>,
}
struct Leaf<P> {
number: usize,
// Inline storage saves one indirection on every successful lookup. The
// factory's Box is consumed before publication; installed pages never move.
page: P,
}
struct Branch {
prefix: usize,
shift: u32,
children: [AtomicPtr<()>; FANOUT],
}
fn digit(number: usize, shift: u32) -> usize {
(number >> shift) & MASK
}
fn prefix(number: usize, shift: u32) -> usize {
// The highest digit may contain fewer than DIGIT bits.
number.checked_shr(shift + DIGIT).unwrap_or(0)
}
fn is_leaf(raw: *mut ()) -> bool {
raw.addr() & 1 != 0
}
fn leaf_ptr<P>(raw: *mut ()) -> *mut Leaf<P> {
// Keep the allocation's provenance while removing the tag.
raw.map_addr(|addr| addr & !1).cast()
}
// SAFETY: the directory owns its pages; moving it transfers that ownership,
// and no page reference can outlive the borrow of the directory.
unsafe impl<P: Send> Send for RadixSpine<P> {}
// SAFETY: shared operations only publish immutable ownership links; pages
// are shared as &P, and a losing installer may drop its own unpublished P.
unsafe impl<P: Send + Sync> Sync for RadixSpine<P> {}
impl<P> RadixSpine<P> {
#[cfg(not(loom))]
pub(crate) const fn new() -> Self {
const {
assert!(mem::align_of::<Leaf<P>>() >= 2);
assert!(mem::align_of::<Branch>() >= 2);
}
Self {
root: AtomicPtr::new(ptr::null_mut()),
owner: PhantomData,
invariant: PhantomData,
}
}
#[cfg(loom)]
pub(crate) fn new() -> Self {
const {
assert!(mem::align_of::<Leaf<P>>() >= 2);
assert!(mem::align_of::<Branch>() >= 2);
}
Self {
root: AtomicPtr::new(ptr::null_mut()),
owner: PhantomData,
invariant: PhantomData,
}
}
pub(crate) fn get(&self, page: usize) -> Option<&P> {
let mut slot = &self.root;
loop {
// Acquire observes the node, page and old-child links published
// by an installer. Shared access never reclaims any of them.
let raw = slot.load(Ordering::Acquire);
if raw.is_null() {
return None;
}
if is_leaf(raw) {
// SAFETY: the tag identifies an initialized Leaf<P>; its
// allocation remains live throughout this shared borrow.
let leaf = unsafe { &*leaf_ptr::<P>(raw) };
return (leaf.number == page).then_some(&leaf.page);
}
// SAFETY: an untagged non-null pointer owns an initialized Branch,
// which cannot be freed during this shared borrow.
let branch = unsafe { &*raw.cast::<Branch>() };
if prefix(page, branch.shift) != branch.prefix {
return None;
}
slot = &branch.children[digit(page, branch.shift)];
}
}
pub(crate) fn get_or_insert_with(&self, page: usize, make: impl FnOnce() -> Box<P>) -> &P {
let mut slot = &self.root;
let mut make = Some(make);
let mut fresh = None;
// Acquire observes any node already installed in the root slot.
let mut old = slot.load(Ordering::Acquire);
loop {
let representative = if old.is_null() {
None
} else if is_leaf(old) {
// SAFETY: this acquired pointer identifies a live Leaf<P>;
// published nodes cannot be reclaimed during shared access.
let leaf = unsafe { &*leaf_ptr::<P>(old) };
if leaf.number == page {
// The guard drops our leaf, if made, when another thread
// has installed the same page number first.
drop(fresh);
return &leaf.page;
}
Some(leaf.number)
} else {
// SAFETY: the acquired untagged pointer is a live Branch;
// its prefix and shift never change after publication.
let branch = unsafe { &*old.cast::<Branch>() };
if prefix(page, branch.shift) == branch.prefix {
slot = &branch.children[digit(page, branch.shift)];
// Acquire observes publication into this child slot.
old = slot.load(Ordering::Acquire);
continue;
}
Some(branch.prefix.checked_shl(branch.shift + DIGIT).unwrap_or(0))
};
let leaf = fresh.get_or_insert_with(|| {
let make = make.take().expect("factory is called at most once");
UnpublishedLeaf(Box::into_raw(Box::new(Leaf {
number: page,
page: *make(),
})))
});
let new_leaf = leaf.0.cast::<()>().map_addr(|addr| addr | 1);
let replacement = if let Some(existing) = representative {
// A prefix mismatch differs above the old branch's digit,
// so this split also strictly decreases shifts down the tree.
let shift = (usize::BITS - 1 - (existing ^ page).leading_zeros()) / DIGIT * DIGIT;
let old_digit = digit(existing, shift);
let new_digit = digit(page, shift);
let branch = Box::new(Branch {
prefix: prefix(page, shift),
shift,
children: core::array::from_fn(|i| {
AtomicPtr::new(if i == old_digit {
old
} else if i == new_digit {
new_leaf
} else {
ptr::null_mut()
})
}),
});
Box::into_raw(branch).cast::<()>()
} else {
new_leaf
};
// Release publishes the initialized leaf/branch and transitively
// the old child's links. Acquire on failure observes the winner.
// Shared changes are only null -> child or child -> a branch
// containing that child, so every installed page stays reachable.
match slot.compare_exchange(old, replacement, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => {
let raw = fresh.take().expect("leaf was just made").into_raw();
// SAFETY: the CAS published this initialized leaf, directly
// or inside the new branch; its guard relinquished ownership
// and shared access prevents reclamation.
return unsafe { &(*raw).page };
}
Err(winner) => {
if representative.is_some() {
// SAFETY: this branch was never published. Its atomic
// pointers do not own/drop the old child or our leaf.
drop(unsafe { Box::from_raw(replacement.cast::<Branch>()) });
}
// Retry this very slot: it may now hold a branch that we
// must descend into. Keep our made leaf across all retries.
// A failed strong CAS means another installer progressed;
// nothing is removed, so this loop is lock-free.
old = winner;
}
}
}
}
/// Installed pages in ascending order, weakly consistent across pages.
/// May miss concurrent installs; every page is yielded at most once.
pub(crate) fn iter(&self) -> SharedPages<'_, P> {
SharedPages {
inner: Walk::new(&self.root, Ordering::Acquire),
marker: PhantomData,
}
}
/// Installed pages in ascending order, with exclusive access to each.
pub(crate) fn iter_mut(&mut self) -> ExclusivePages<'_, P> {
ExclusivePages {
inner: Walk::new(&self.root, Ordering::Relaxed),
marker: PhantomData,
}
}
/// Drops the installed page and collapses branches with only one child.
pub(crate) fn remove(&mut self, number: usize) {
// Drop the leaf after relinking the tree, in case its destructor panics.
drop(Self::unlink_leaf(&mut self.root, number));
}
fn unlink_leaf(slot: &mut AtomicPtr<()>, number: usize) -> Option<Box<Leaf<P>>> {
// The caller has exclusive directory access for this whole traversal.
let raw = slot.load(Ordering::Relaxed);
if raw.is_null() {
return None;
}
if is_leaf(raw) {
let leaf = leaf_ptr::<P>(raw);
// SAFETY: the tag identifies a live leaf owned by this slot.
if unsafe { (*leaf).number } != number {
return None;
}
slot.store(ptr::null_mut(), Ordering::Relaxed);
// SAFETY: the store detached the leaf, transferring its sole ownership.
return Some(unsafe { Box::from_raw(leaf) });
}
// SAFETY: this exclusively borrowed link owns the installed branch.
// Recursing on a child cannot free this branch.
let branch = unsafe { &mut *raw.cast::<Branch>() };
if prefix(number, branch.shift) != branch.prefix {
return None;
}
let child = digit(number, branch.shift);
let removed = Self::unlink_leaf(&mut branch.children[child], number)?;
let mut children = branch
.children
.iter()
.map(|child| child.load(Ordering::Relaxed))
.filter(|child| !child.is_null());
let first = children.next().expect("branch had at least two children");
if children.next().is_none() {
slot.store(first, Ordering::Relaxed);
// SAFETY: the branch is detached and its only live child is now
// linked from the parent. Dropping the branch drops no children.
drop(unsafe { Box::from_raw(raw.cast::<Branch>()) });
}
Some(removed)
}
/// Frees every node and page. The root is detached first, and a cleanup
/// guard keeps freeing the remaining nodes if one page destructor panics.
/// A second destructor panic during unwinding aborts as usual.
pub(crate) fn clear(&mut self) {
// Relaxed suffices: exclusive access rules out readers/installers.
let raw = self.root.swap(ptr::null_mut(), Ordering::Relaxed);
let mut reclaim = Reclaim::<P> {
nodes: Vec::new(),
owner: PhantomData,
};
if !raw.is_null() {
reclaim.nodes.push(raw);
}
reclaim.drain();
}
}
/// Owns the made leaf until publication, including across failed splits.
struct UnpublishedLeaf<P>(*mut Leaf<P>);
impl<P> UnpublishedLeaf<P> {
fn into_raw(self) -> *mut Leaf<P> {
let raw = self.0;
mem::forget(self);
raw
}
}
impl<P> Drop for UnpublishedLeaf<P> {
fn drop(&mut self) {
// SAFETY: this guard uniquely owns a Box that was never published.
drop(unsafe { Box::from_raw(self.0) });
}
}
/// DFS frames borrow slots, not their contents. Each slot is loaded once.
/// If a split happens after that load, this walk keeps the old child and
/// never visits its new ancestor. If before, it visits the new branch and
/// then its old child once. Parent slots have disjoint ordered ranges, so
/// neither case can duplicate a leaf or put it out of ascending order.
struct Walk<'a> {
levels: [slice::Iter<'a, AtomicPtr<()>>; WALK_LEVELS],
depth: usize,
ordering: Ordering,
}
impl<'a> Walk<'a> {
fn new(root: &'a AtomicPtr<()>, ordering: Ordering) -> Self {
let mut levels = core::array::from_fn(|_| slice::Iter::default());
levels[0] = slice::from_ref(root).iter();
Self {
levels,
depth: 1,
ordering,
}
}
}
impl Iterator for Walk<'_> {
type Item = *mut ();
fn next(&mut self) -> Option<Self::Item> {
while self.depth > 0 {
let level = &mut self.levels[self.depth - 1];
let Some(slot) = level.next() else {
self.depth -= 1;
continue;
};
// Acquire observes node/page publication for shared iteration;
// Relaxed suffices when an exclusive iterator borrows the directory.
let raw = slot.load(self.ordering);
if raw.is_null() {
continue;
}
if is_leaf(raw) {
return Some(raw);
}
// SAFETY: the owning iterator borrows the directory, preventing
// reclamation of this installed Branch and its initialized slots.
let branch = unsafe { &*raw.cast::<Branch>() };
self.levels[self.depth] = branch.children.iter();
self.depth += 1;
}
None
}
}
/// Shared traversal over installed radix pages.
pub(crate) struct SharedPages<'a, P> {
inner: Walk<'a>,
// Match the auto traits of a shared directory borrow, like Spine::iter.
marker: PhantomData<&'a RadixSpine<P>>,
}
impl<'a, P> Iterator for SharedPages<'a, P> {
type Item = (usize, &'a P);
fn next(&mut self) -> Option<Self::Item> {
let raw = self.inner.next()?;
// SAFETY: Walk yields only initialized installed leaves, whose
// allocations remain live for the iterator's shared directory borrow.
let leaf = unsafe { &*leaf_ptr::<P>(raw) };
Some((leaf.number, &leaf.page))
}
}
/// Carries `&mut P`'s auto traits for RadixSpine::iter_mut, like Spine's adapter.
pub(crate) struct ExclusivePages<'a, P> {
inner: Walk<'a>,
marker: PhantomData<&'a mut P>,
}
impl<'a, P> Iterator for ExclusivePages<'a, P> {
type Item = (usize, &'a mut P);
fn next(&mut self) -> Option<Self::Item> {
let raw = self.inner.next()?;
// SAFETY: exclusive access prevents other page borrows or installers;
// Walk visits each distinct owned leaf once, even across next calls.
let leaf = unsafe { &mut *leaf_ptr::<P>(raw) };
Some((leaf.number, &mut leaf.page))
}
}
/// Detached ownership, with a second drain on unwinding after a page panic.
struct Reclaim<P> {
nodes: Vec<*mut ()>,
owner: PhantomData<Box<P>>,
}
impl<P> Reclaim<P> {
fn drain(&mut self) {
while let Some(raw) = self.nodes.pop() {
if is_leaf(raw) {
// SAFETY: the detached tree uniquely owns every leaf, and
// popping first prevents a second drop if P::drop panics.
drop(unsafe { Box::from_raw(leaf_ptr::<P>(raw)) });
} else {
// SAFETY: each untagged pointer uniquely owns a Branch in the
// detached tree; no directory borrows or other owners remain.
let branch = unsafe { Box::from_raw(raw.cast::<Branch>()) };
for slot in &branch.children {
// Relaxed suffices: this entire tree is exclusively owned.
let child = slot.load(Ordering::Relaxed);
if !child.is_null() {
self.nodes.push(child);
}
}
}
}
}
}
impl<P> Drop for Reclaim<P> {
fn drop(&mut self) {
self.drain();
}
}
impl<P> Drop for RadixSpine<P> {
fn drop(&mut self) {
self.clear();
}
}
#[cfg(test)]
impl<P> RadixSpine<P> {
/// Checks a quiescent tree; callers must first join any installers.
pub(super) fn check(&self) {
let mut nodes = Vec::new();
let mut numbers = Vec::new();
// Acquire observes the installed root's initialization.
let root = self.root.load(Ordering::Acquire);
if !root.is_null() {
nodes.push((root, None));
}
while let Some((raw, parent)) = nodes.pop() {
let (number, shift) = if is_leaf(raw) {
// SAFETY: this acquired pointer identifies an installed leaf,
// which stays allocated throughout the check's shared borrow.
let leaf = unsafe { &*leaf_ptr::<P>(raw) };
numbers.push(leaf.number);
(leaf.number, None)
} else {
// SAFETY: the acquired untagged pointer is an installed Branch
// and its allocation stays live during this shared borrow.
let branch = unsafe { &*raw.cast::<Branch>() };
assert_eq!(branch.shift % DIGIT, 0);
assert!(branch.shift < usize::BITS);
let number = branch.prefix.checked_shl(branch.shift + DIGIT).unwrap_or(0);
assert_eq!(prefix(number, branch.shift), branch.prefix);
let mut occupied = 0;
for (i, slot) in branch.children.iter().enumerate().rev() {
// Acquire observes the child's initialization.
let child = slot.load(Ordering::Acquire);
if !child.is_null() {
occupied += 1;
nodes.push((child, Some((branch.prefix, branch.shift, i))));
}
}
assert!(occupied >= 2);
(number, Some(branch.shift))
};
if let Some((parent_prefix, parent_shift, index)) = parent {
assert_eq!(prefix(number, parent_shift), parent_prefix);
assert_eq!(digit(number, parent_shift), index);
if let Some(shift) = shift {
assert!(shift < parent_shift);
}
}
}
assert!(numbers.windows(2).all(|pair| pair[0] < pair[1]));
assert_eq!(self.iter().map(|(n, _)| n).collect::<Vec<_>>(), numbers);
}
}
#[cfg(all(test, not(loom)))]
mod tests {
use super::*;
use alloc::collections::BTreeMap;
use alloc::sync::Arc;
use core::cell::Cell;
use core::sync::atomic::AtomicUsize;
use proptest::prelude::*;
fn assert_contents(spine: &RadixSpine<u32>, expected: &BTreeMap<usize, u32>, probe: usize) {
for (&number, value) in expected {
assert_eq!(spine.get(number), Some(value));
}
for number in [0, 1, usize::MAX, probe, probe.wrapping_add(1), probe ^ 1] {
assert_eq!(spine.get(number), expected.get(&number));
}
let absent = (0..).find(|n| !expected.contains_key(n)).unwrap();
assert!(spine.get(absent).is_none());
assert_eq!(
spine
.iter()
.map(|(n, value)| (n, *value))
.collect::<Vec<_>>(),
expected
.iter()
.map(|(&n, &value)| (n, value))
.collect::<Vec<_>>()
);
spine.check();
}
#[test]
fn random_operations_match_btree_map() {
let config = proptest::test_runner::Config {
cases: if cfg!(miri) { 4 } else { 256 },
failure_persistence: None,
..proptest::test_runner::Config::default()
};
let operations = proptest::collection::vec(
(0_u8..8, any::<usize>(), 0_u8..5, any::<u32>()),
1..if cfg!(miri) { 16 } else { 160 },
);
proptest::test_runner::TestRunner::new(config)
.run(&operations, |operations| {
let mut spine = RadixSpine::new();
let mut expected = BTreeMap::new();
for (op, raw, region, value) in operations {
let number = match region {
0 => raw % 256,
1 => usize::MAX - raw % 256,
2 => ((usize::MAX / 3) & !MASK) | (raw & MASK),
3 => (usize::MAX & !0xfff) | (raw & 0xfff),
_ => raw,
};
match op {
0..=4 => {
let called = Cell::new(false);
let present = expected.contains_key(&number);
// Moving the Box into the closure also exercises a
// factory that only implements FnOnce.
let made = Box::new(value);
let page = spine.get_or_insert_with(number, || {
assert!(!called.replace(true));
made
});
assert_eq!(*page, *expected.entry(number).or_insert(value));
assert_eq!(called.get(), !present);
}
5 => assert_eq!(spine.get(number), expected.get(&number)),
6 => {
for (_, page) in spine.iter_mut() {
*page ^= value;
}
for page in expected.values_mut() {
*page ^= value;
}
}
_ => {
spine.clear();
expected.clear();
}
}
assert_contents(&spine, &expected, number);
}
Ok(())
})
.unwrap();
}
#[test]
fn every_digit_and_the_partial_top_digit() {
let spine = RadixSpine::new();
let mut expected = BTreeMap::new();
let numbers: Vec<_> = (0..usize::BITS)
.step_by(DIGIT as usize)
.flat_map(|shift| {
let boundary = 1_usize << shift;
[boundary - 1, boundary, boundary + 1]
})
.chain([usize::MAX, usize::MAX - 1])
.collect();
// The reversed order exercises splitting above branches as well as
// extending their subtrees at progressively lower digits.
for (i, number) in numbers.into_iter().rev().enumerate() {
let value = i as u32;
assert_eq!(
*spine.get_or_insert_with(number, || Box::new(value)),
*expected.entry(number).or_insert(value)
);
assert_contents(&spine, &expected, number);
}
}
#[test]
fn exclusive_iteration_clear_and_reuse() {
const fn empty() -> RadixSpine<u32> {
RadixSpine::new()
}
let mut spine = empty();
assert!(spine.get(usize::MAX).is_none());
assert_eq!(spine.iter().count(), 0);
assert_eq!(spine.iter_mut().count(), 0);
spine.clear();
let numbers = [0, 1, 64, 1 << (usize::BITS - 1), usize::MAX];
for number in numbers.into_iter().rev() {
spine.get_or_insert_with(number, || Box::new(1));
}
let addresses: Vec<_> = spine.iter().map(|(_, p)| ptr::from_ref(p)).collect();
// Hold all mutable references together to exercise disjointness.
let pages: Vec<_> = spine.iter_mut().collect();
for (i, (number, page)) in pages.into_iter().enumerate() {
assert_eq!(number, numbers[i]);
assert_eq!(ptr::from_mut(page).cast_const(), addresses[i]);
*page += i as u32;
}
assert_eq!(
spine.iter().map(|(_, page)| *page).collect::<Vec<_>>(),
[1, 2, 3, 4, 5]
);
for number in [1, 64, 0, usize::MAX] {
spine.remove(number);
assert!(spine.get(number).is_none());
spine.check();
}
spine.remove(1);
let surviving = spine.get(1 << (usize::BITS - 1)).unwrap();
assert_eq!(ptr::from_ref(surviving), addresses[3]);
assert_eq!(*surviving, 4);
assert_eq!(*spine.get_or_insert_with(64, || Box::new(7)), 7);
spine.check();
spine.clear();
spine.check();
for number in numbers {
assert!(spine.get(number).is_none());
}
assert_eq!(*spine.get_or_insert_with(usize::MAX, || Box::new(9)), 9);
spine.check();
}
#[test]
fn zero_sized_pages_and_auto_traits() {
fn assert_send<T: Send>(_: T) {}
fn assert_sync<T: Sync>(_: &T) {}
let spine = RadixSpine::new();
for number in [0, usize::MAX] {
spine.get_or_insert_with(number, || Box::new(()));
}
assert_eq!(
spine.iter().map(|(n, _)| n).collect::<Vec<_>>(),
[0, usize::MAX]
);
spine.check();
assert_sync(&spine);
assert_sync(&spine.iter());
assert_send(spine.iter());
assert_send(spine);
// A Cell page is Send but not Sync. Exclusive iteration must retain
// the auto traits of &mut P rather than those of a shared directory.
let mut spine = RadixSpine::<Cell<u32>>::new();
spine.get_or_insert_with(0, || Box::new(Cell::new(7)));
assert_send(spine.iter_mut());
assert_send(spine);
}
struct CountedPage {
number: usize,
dropped: Arc<AtomicUsize>,
}
impl Drop for CountedPage {
fn drop(&mut self) {
assert_eq!(self.dropped.fetch_add(1, Ordering::Relaxed), 0);
}
}
#[test]
fn each_installed_page_is_dropped_once() {
let mut spine = RadixSpine::new();
let mut counters = Vec::new();
for number in [0, 64, usize::MAX, usize::MAX - 1] {
let dropped = Arc::new(AtomicUsize::new(0));
counters.push(dropped.clone());
spine.get_or_insert_with(number, || Box::new(CountedPage { number, dropped }));
let page = spine.get_or_insert_with(number, || panic!("factory must stay lazy"));
assert_eq!(page.number, number);
}
assert!(counters.iter().all(|n| n.load(Ordering::Relaxed) == 0));
spine.clear();
assert!(counters.iter().all(|n| n.load(Ordering::Relaxed) == 1));
let dropped = Arc::new(AtomicUsize::new(0));
let reused = dropped.clone();
spine.get_or_insert_with(usize::MAX, || {
Box::new(CountedPage {
number: usize::MAX,
dropped: reused,
})
});
drop(spine);
assert_eq!(dropped.load(Ordering::Relaxed), 1);
assert!(counters.iter().all(|n| n.load(Ordering::Relaxed) == 1));
}
#[cfg(feature = "std")]
#[test]
fn clear_keeps_freeing_after_a_page_panics() {
use std::panic::{AssertUnwindSafe, catch_unwind};
struct PanickingPage {
dropped: Arc<AtomicUsize>,
panic: bool,
}
impl Drop for PanickingPage {
fn drop(&mut self) {
self.dropped.fetch_add(1, Ordering::Relaxed);
assert!(!self.panic, "page destructor failed");
}
}
let mut spine = RadixSpine::new();
let counters: Vec<_> = (0..3).map(|_| Arc::new(AtomicUsize::new(0))).collect();
for (i, number) in [0, 1, usize::MAX].into_iter().enumerate() {
spine.get_or_insert_with(number, || {
Box::new(PanickingPage {
dropped: counters[i].clone(),
// Reclamation visits the highest child first, leaving
// both other leaves for the unwind cleanup guard.
panic: number == usize::MAX,
})
});
}
assert!(catch_unwind(AssertUnwindSafe(|| spine.clear())).is_err());
assert!(counters.iter().all(|n| n.load(Ordering::Relaxed) == 1));
assert_eq!(spine.iter().count(), 0);
spine.check();
assert!(
catch_unwind(AssertUnwindSafe(|| {
spine.get_or_insert_with(3, || panic!("factory failed"));
}))
.is_err()
);
spine.check();
spine.get_or_insert_with(4, || {
Box::new(PanickingPage {
dropped: counters[0].clone(),
panic: false,
})
});
drop(spine);
assert_eq!(counters[0].load(Ordering::Relaxed), 2);
}
#[cfg(feature = "std")]
#[test]
fn overlapping_thread_installs_keep_one_page_per_number() {
use std::sync::Barrier;
use std::thread;
let spine = Arc::new(RadixSpine::new());
let gate = Arc::new(Barrier::new(8));
let numbers: Arc<Vec<_>> = Arc::new(
(0..64)
.flat_map(|n| [n, usize::MAX - n, ((usize::MAX / 3) & !MASK) | n])
.collect(),
);
let threads: Vec<_> = (0..8)
.map(|thread_number| {
let spine = spine.clone();
let gate = gate.clone();
let numbers = numbers.clone();
thread::spawn(move || {
let mut made = Vec::new();
let mut install = |number, first| {
let page = spine.get_or_insert_with(number, || {
let dropped = Arc::new(AtomicUsize::new(0));
made.push(dropped.clone());
if first {
// Force eight factories for the first page,
// so losing allocations are always exercised.
gate.wait();
}
Box::new(CountedPage { number, dropped })
});
assert_eq!(page.number, number);
(number, ptr::from_ref(page).addr())
};
let mut addresses = alloc::vec![install(numbers[0], true)];
for offset in 1..numbers.len() {
let i = 1 + (offset - 1 + thread_number * 17) % (numbers.len() - 1);
addresses.push(install(numbers[i], false));
}
addresses.sort_unstable();
(addresses, made)
})
})
.collect();
let results: Vec<_> = threads.into_iter().map(|t| t.join().unwrap()).collect();
for (addresses, _) in &results {
assert_eq!(*addresses, results[0].0);
}
assert_eq!(spine.iter().count(), numbers.len());
spine.check();
let counters: Vec<_> = results.into_iter().flat_map(|(_, made)| made).collect();
assert!(counters.len() >= numbers.len() + 7);
let dropped: usize = counters.iter().map(|n| n.load(Ordering::Relaxed)).sum();
assert_eq!(counters.len() - dropped, numbers.len());
assert!(counters.iter().all(|n| n.load(Ordering::Relaxed) <= 1));
let mut spine = Arc::try_unwrap(spine).ok().unwrap();
spine.clear();
assert!(counters.iter().all(|n| n.load(Ordering::Relaxed) == 1));
drop(spine);
assert!(counters.iter().all(|n| n.load(Ordering::Relaxed) == 1));
}
}