cachekit 0.1.0-alpha

High-performance, policy-driven cache primitives for Rust systems (FIFO/LRU/ARC) with optional metrics.
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
//! Slot arena with stable `SlotId` handles.
//!
//! Stores elements in a `Vec<Option<T>>` and reuses freed slots via a free list.
//! This keeps indices stable and avoids per-operation allocation.
//!
//! ## Architecture
//!
//! ```text
//!   slots: Vec<Option<T>>
//!   free_list: Vec<usize>
//!
//!   index: 0     1     2     3
//!          [T]  [ ]   [T]   [ ]
//!                 ^         ^
//!                 |         |
//!             free_list = [1, 3]
//! ```
//!
//! ## Operations
//! - `insert(value)`: uses a free slot if available, otherwise grows `slots`
//! - `remove(id)`: clears slot and pushes index to `free_list`
//! - `get(id)`: returns `None` if slot is empty or out of bounds
//!
//! ## Performance
//! - `insert` / `remove` / `get`: O(1) average
//! - `iter`: O(n) over slots
//!
//! `debug_validate_invariants()` is available in debug/test builds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Stable handle into a `SlotArena`.
///
/// `SlotId` values remain valid until the referenced slot is removed; after
/// removal, the numeric index may be reused by a later `insert`.
pub struct SlotId(pub(crate) usize);

impl SlotId {
    /// Returns the underlying slot index.
    pub fn index(self) -> usize {
        self.0
    }
}

#[derive(Debug)]
/// Arena that stores values in reusable slots and returns stable `SlotId`s.
pub struct SlotArena<T> {
    slots: Vec<Option<T>>,
    free_list: Vec<usize>,
    len: usize,
}

impl<T> SlotArena<T> {
    /// Creates an empty arena.
    pub fn new() -> Self {
        Self {
            slots: Vec::new(),
            free_list: Vec::new(),
            len: 0,
        }
    }

    /// Creates an empty arena with reserved capacity for slots.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            slots: Vec::with_capacity(capacity),
            free_list: Vec::new(),
            len: 0,
        }
    }

    /// Inserts a value and returns its `SlotId`.
    pub fn insert(&mut self, value: T) -> SlotId {
        let idx = if let Some(idx) = self.free_list.pop() {
            self.slots[idx] = Some(value);
            idx
        } else {
            self.slots.push(Some(value));
            self.slots.len() - 1
        };
        self.len += 1;
        SlotId(idx)
    }

    /// Removes the value at `id` and returns it, or `None` if empty/out of bounds.
    pub fn remove(&mut self, id: SlotId) -> Option<T> {
        let slot = self.slots.get_mut(id.0)?;
        let value = slot.take()?;
        self.free_list.push(id.0);
        self.len -= 1;
        Some(value)
    }

    /// Returns a shared reference to the value at `id`, if present.
    pub fn get(&self, id: SlotId) -> Option<&T> {
        self.slots.get(id.0).and_then(|slot| slot.as_ref())
    }

    /// Returns a mutable reference to the value at `id`, if present.
    pub fn get_mut(&mut self, id: SlotId) -> Option<&mut T> {
        self.slots.get_mut(id.0).and_then(|slot| slot.as_mut())
    }

    /// Returns `true` if `id` currently refers to a live slot.
    pub fn contains(&self, id: SlotId) -> bool {
        self.slots
            .get(id.0)
            .map(|slot| slot.is_some())
            .unwrap_or(false)
    }

    /// Returns `true` if the slot at `index` is in bounds and occupied.
    pub fn contains_index(&self, index: usize) -> bool {
        self.slots
            .get(index)
            .map(|slot| slot.is_some())
            .unwrap_or(false)
    }

    /// Returns the number of live entries.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if the arena has no live entries.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the backing vector capacity (number of slots that can be held without realloc).
    pub fn capacity(&self) -> usize {
        self.slots.capacity()
    }

    /// Reserves capacity for at least `additional` more slots.
    pub fn reserve_slots(&mut self, additional: usize) {
        self.slots.reserve(additional);
    }

    /// Shrinks internal storage to fit the current length.
    pub fn shrink_to_fit(&mut self) {
        self.slots.shrink_to_fit();
        self.free_list.shrink_to_fit();
    }

    /// Clears all entries and shrinks internal storage.
    pub fn clear_shrink(&mut self) {
        self.clear();
        self.shrink_to_fit();
    }

    /// Removes all entries and resets internal state.
    pub fn clear(&mut self) {
        self.slots.clear();
        self.free_list.clear();
        self.len = 0;
    }

    /// Iterates over live `(SlotId, &T)` pairs.
    pub fn iter(&self) -> impl Iterator<Item = (SlotId, &T)> {
        self.slots
            .iter()
            .enumerate()
            .filter_map(|(idx, slot)| slot.as_ref().map(|value| (SlotId(idx), value)))
    }

    /// Iterates over live SlotIds.
    pub fn iter_ids(&self) -> impl Iterator<Item = SlotId> + '_ {
        self.slots
            .iter()
            .enumerate()
            .filter_map(|(idx, slot)| slot.as_ref().map(|_| SlotId(idx)))
    }

    #[cfg(any(test, debug_assertions))]
    /// Returns a debug snapshot of arena internals.
    pub fn debug_snapshot(&self) -> SlotArenaSnapshot {
        let mut free_list = self.free_list.clone();
        free_list.sort_unstable();
        let mut live_ids: Vec<_> = self.iter_ids().collect();
        live_ids.sort_by_key(|id| id.index());
        SlotArenaSnapshot {
            len: self.len,
            slots_len: self.slots.len(),
            free_list,
            live_ids,
        }
    }

    /// Returns an approximate memory footprint in bytes.
    pub fn approx_bytes(&self) -> usize {
        std::mem::size_of::<Self>()
            + self.slots.capacity() * std::mem::size_of::<Option<T>>()
            + self.free_list.capacity() * std::mem::size_of::<usize>()
    }

    #[cfg(any(test, debug_assertions))]
    pub fn debug_validate_invariants(&self) {
        let live_count = self.slots.iter().filter(|slot| slot.is_some()).count();
        assert_eq!(self.len, live_count);
        assert!(self.len <= self.slots.len());

        let mut seen_free = std::collections::HashSet::new();
        for &idx in &self.free_list {
            assert!(idx < self.slots.len());
            assert!(self.slots[idx].is_none());
            assert!(seen_free.insert(idx));
        }

        assert_eq!(self.slots.len(), self.free_list.len() + self.len);
    }
}

#[cfg(any(test, debug_assertions))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SlotArenaSnapshot {
    pub len: usize,
    pub slots_len: usize,
    pub free_list: Vec<usize>,
    pub live_ids: Vec<SlotId>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Stable handle into a `ShardedSlotArena`.
pub struct ShardedSlotId {
    shard: usize,
    slot: SlotId,
}

impl ShardedSlotId {
    /// Returns the shard index.
    pub fn shard(self) -> usize {
        self.shard
    }

    /// Returns the slot id within the shard.
    pub fn slot(self) -> SlotId {
        self.slot
    }
}

#[derive(Debug)]
/// SlotArena sharded by a fixed number of `RwLock`-protected arenas.
pub struct ShardedSlotArena<T> {
    shards: Vec<parking_lot::RwLock<SlotArena<T>>>,
    selector: crate::ds::ShardSelector,
    next_shard: std::sync::atomic::AtomicUsize,
}

impl<T> ShardedSlotArena<T> {
    /// Creates a sharded arena with `shards` shards.
    pub fn new(shards: usize) -> Self {
        let shards = shards.max(1);
        let mut arenas = Vec::with_capacity(shards);
        for _ in 0..shards {
            arenas.push(parking_lot::RwLock::new(SlotArena::new()));
        }
        Self {
            shards: arenas,
            selector: crate::ds::ShardSelector::new(shards, 0),
            next_shard: std::sync::atomic::AtomicUsize::new(0),
        }
    }

    /// Creates a sharded arena with `shards` shards, each pre-allocated to `capacity`.
    pub fn with_capacity(shards: usize, capacity: usize) -> Self {
        let shards = shards.max(1);
        let mut arenas = Vec::with_capacity(shards);
        for _ in 0..shards {
            arenas.push(parking_lot::RwLock::new(SlotArena::with_capacity(capacity)));
        }
        Self {
            shards: arenas,
            selector: crate::ds::ShardSelector::new(shards, 0),
            next_shard: std::sync::atomic::AtomicUsize::new(0),
        }
    }

    /// Creates a sharded arena with `shards`, each pre-allocated to `capacity_per_shard`.
    pub fn with_shards(shards: usize, capacity_per_shard: usize) -> Self {
        Self::with_capacity(shards, capacity_per_shard)
    }

    /// Creates a sharded arena with `shards`, `capacity_per_shard`, and a hash seed.
    pub fn with_shards_seed(shards: usize, capacity_per_shard: usize, seed: u64) -> Self {
        let shards = shards.max(1);
        let mut arenas = Vec::with_capacity(shards);
        for _ in 0..shards {
            arenas.push(parking_lot::RwLock::new(SlotArena::with_capacity(
                capacity_per_shard,
            )));
        }
        Self {
            shards: arenas,
            selector: crate::ds::ShardSelector::new(shards, seed),
            next_shard: std::sync::atomic::AtomicUsize::new(0),
        }
    }

    /// Returns the shard index for `key` using the configured selector.
    pub fn shard_for_key<K: std::hash::Hash>(&self, key: &K) -> usize {
        self.selector.shard_for_key(key)
    }

    /// Returns the number of shards.
    pub fn shard_count(&self) -> usize {
        self.shards.len()
    }

    /// Inserts a value into a selected shard and returns its `ShardedSlotId`.
    pub fn insert(&self, value: T) -> ShardedSlotId {
        let shard = self
            .next_shard
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
            % self.shards.len();
        let mut arena = self.shards[shard].write();
        let slot = arena.insert(value);
        ShardedSlotId { shard, slot }
    }

    /// Removes the value at `id` and returns it, if present.
    pub fn remove(&self, id: ShardedSlotId) -> Option<T> {
        let mut arena = self.shards.get(id.shard)?.write();
        arena.remove(id.slot)
    }

    /// Runs `f` on a shared reference to the value at `id`, if present.
    pub fn get_with<R>(&self, id: ShardedSlotId, f: impl FnOnce(&T) -> R) -> Option<R> {
        let arena = self.shards.get(id.shard)?.read();
        arena.get(id.slot).map(f)
    }

    /// Runs `f` on a mutable reference to the value at `id`, if present.
    pub fn get_mut_with<R>(&self, id: ShardedSlotId, f: impl FnOnce(&mut T) -> R) -> Option<R> {
        let mut arena = self.shards.get(id.shard)?.write();
        arena.get_mut(id.slot).map(f)
    }

    /// Returns `true` if `id` currently refers to a live slot.
    pub fn contains(&self, id: ShardedSlotId) -> bool {
        self.shards
            .get(id.shard)
            .map(|arena| arena.read().contains(id.slot))
            .unwrap_or(false)
    }

    /// Returns the number of live entries across all shards.
    pub fn len(&self) -> usize {
        self.shards.iter().map(|arena| arena.read().len()).sum()
    }

    /// Returns `true` if all shards are empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Reserves capacity for at least `additional` more slots in each shard.
    pub fn reserve_slots(&self, additional: usize) {
        for arena in &self.shards {
            arena.write().reserve_slots(additional);
        }
    }

    /// Shrinks all shards to fit their current lengths.
    pub fn shrink_to_fit(&self) {
        for arena in &self.shards {
            arena.write().shrink_to_fit();
        }
    }

    /// Clears all shards and shrinks internal storage.
    pub fn clear_shrink(&self) {
        for arena in &self.shards {
            arena.write().clear_shrink();
        }
    }

    /// Returns an approximate memory footprint in bytes.
    pub fn approx_bytes(&self) -> usize {
        self.shards
            .iter()
            .map(|arena| arena.read().approx_bytes())
            .sum()
    }
}

impl<T> Default for SlotArena<T> {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug)]
/// Thread-safe wrapper around `SlotArena` using a `parking_lot::RwLock`.
pub struct ConcurrentSlotArena<T> {
    inner: parking_lot::RwLock<SlotArena<T>>,
}

impl<T> ConcurrentSlotArena<T> {
    /// Creates an empty concurrent arena.
    pub fn new() -> Self {
        Self {
            inner: parking_lot::RwLock::new(SlotArena::new()),
        }
    }

    /// Creates an empty concurrent arena with reserved slot capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            inner: parking_lot::RwLock::new(SlotArena::with_capacity(capacity)),
        }
    }

    /// Inserts a value and returns its `SlotId`.
    pub fn insert(&self, value: T) -> SlotId {
        let mut arena = self.inner.write();
        arena.insert(value)
    }

    /// Removes the value at `id` and returns it, if present.
    pub fn remove(&self, id: SlotId) -> Option<T> {
        let mut arena = self.inner.write();
        arena.remove(id)
    }

    /// Runs `f` on a shared reference to the value at `id`, if present.
    pub fn get_with<R>(&self, id: SlotId, f: impl FnOnce(&T) -> R) -> Option<R> {
        let arena = self.inner.read();
        arena.get(id).map(f)
    }

    /// Tries to run `f` on a shared reference to the value at `id` without blocking.
    pub fn try_get_with<R>(&self, id: SlotId, f: impl FnOnce(&T) -> R) -> Option<R> {
        let arena = self.inner.try_read()?;
        arena.get(id).map(f)
    }

    /// Runs `f` on a mutable reference to the value at `id`, if present.
    pub fn get_mut_with<R>(&self, id: SlotId, f: impl FnOnce(&mut T) -> R) -> Option<R> {
        let mut arena = self.inner.write();
        arena.get_mut(id).map(f)
    }

    /// Tries to run `f` on a mutable reference to the value at `id` without blocking.
    pub fn try_get_mut_with<R>(&self, id: SlotId, f: impl FnOnce(&mut T) -> R) -> Option<R> {
        let mut arena = self.inner.try_write()?;
        arena.get_mut(id).map(f)
    }

    /// Returns `true` if `id` currently refers to a live slot.
    pub fn contains(&self, id: SlotId) -> bool {
        let arena = self.inner.read();
        arena.contains(id)
    }

    /// Returns the number of live entries.
    pub fn len(&self) -> usize {
        let arena = self.inner.read();
        arena.len()
    }

    /// Returns `true` if there are no live entries.
    pub fn is_empty(&self) -> bool {
        let arena = self.inner.read();
        arena.is_empty()
    }

    /// Returns the backing vector capacity.
    pub fn capacity(&self) -> usize {
        let arena = self.inner.read();
        arena.capacity()
    }

    /// Reserves capacity for at least `additional` more slots.
    pub fn reserve_slots(&self, additional: usize) {
        let mut arena = self.inner.write();
        arena.reserve_slots(additional);
    }

    /// Shrinks internal storage to fit the current length.
    pub fn shrink_to_fit(&self) {
        let mut arena = self.inner.write();
        arena.shrink_to_fit();
    }

    /// Clears all entries and shrinks internal storage.
    pub fn clear_shrink(&self) {
        let mut arena = self.inner.write();
        arena.clear_shrink();
    }

    /// Clears all entries.
    pub fn clear(&self) {
        let mut arena = self.inner.write();
        arena.clear();
    }

    /// Returns an approximate memory footprint in bytes.
    pub fn approx_bytes(&self) -> usize {
        let arena = self.inner.read();
        arena.approx_bytes()
    }
}

impl<T> Default for ConcurrentSlotArena<T> {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn slot_arena_insert_remove_reuse() {
        let mut arena = SlotArena::new();
        let id1 = arena.insert("a");
        let id2 = arena.insert("b");
        assert_eq!(arena.len(), 2);
        assert_eq!(arena.get(id1), Some(&"a"));
        assert_eq!(arena.get(id2), Some(&"b"));

        assert_eq!(arena.remove(id1), Some("a"));
        assert_eq!(arena.len(), 1);

        let id3 = arena.insert("c");
        assert_eq!(arena.len(), 2);
        assert_eq!(arena.get(id3), Some(&"c"));
        assert_eq!(id1.index(), id3.index());
    }

    #[test]
    fn concurrent_slot_arena_basic_ops() {
        let arena = ConcurrentSlotArena::new();
        let id = arena.insert(10);
        assert_eq!(arena.get_with(id, |v| *v), Some(10));
        assert!(arena.contains(id));
        assert_eq!(arena.len(), 1);

        arena.get_mut_with(id, |v| *v = 20);
        assert_eq!(arena.get_with(id, |v| *v), Some(20));
        assert_eq!(arena.remove(id), Some(20));
        assert!(!arena.contains(id));
        assert!(arena.is_empty());
    }

    #[test]
    fn slot_arena_remove_invalid_id_is_none() {
        let mut arena: SlotArena<i32> = SlotArena::new();
        let id = SlotId(0);
        assert_eq!(arena.remove(id), None);
        assert!(!arena.contains(id));
        assert!(arena.is_empty());
    }

    #[test]
    fn slot_arena_clear_resets_state() {
        let mut arena = SlotArena::with_capacity(4);
        let a = arena.insert("a");
        let b = arena.insert("b");
        assert_eq!(arena.len(), 2);
        assert!(arena.contains(a));
        assert!(arena.contains(b));

        arena.clear();
        assert_eq!(arena.len(), 0);
        assert!(arena.is_empty());
        assert!(!arena.contains(a));
        assert!(!arena.contains(b));
        assert_eq!(arena.iter().count(), 0);
    }

    #[test]
    fn slot_arena_iter_skips_empty_slots() {
        let mut arena = SlotArena::new();
        let a = arena.insert("a");
        let b = arena.insert("b");
        let c = arena.insert("c");
        assert_eq!(arena.remove(b), Some("b"));

        let mut values: Vec<_> = arena.iter().map(|(_, v)| *v).collect();
        values.sort();
        assert_eq!(values, vec!["a", "c"]);
        assert!(arena.contains(a));
        assert!(arena.contains(c));
    }

    #[test]
    fn slot_arena_get_mut_updates_value() {
        let mut arena = SlotArena::new();
        let id = arena.insert(1);
        if let Some(value) = arena.get_mut(id) {
            *value = 2;
        }
        assert_eq!(arena.get(id), Some(&2));
    }

    #[test]
    fn slot_arena_capacity_tracking() {
        let arena: SlotArena<i32> = SlotArena::with_capacity(16);
        assert!(arena.capacity() >= 16);
        assert_eq!(arena.len(), 0);
    }

    #[test]
    fn slot_arena_contains_index_and_iter_ids() {
        let mut arena = SlotArena::new();
        let a = arena.insert("a");
        let b = arena.insert("b");
        assert!(arena.contains_index(a.index()));
        assert!(arena.contains_index(b.index()));
        arena.remove(a);
        assert!(!arena.contains_index(a.index()));

        let ids: Vec<_> = arena.iter_ids().collect();
        assert_eq!(ids, vec![b]);
    }

    #[test]
    fn slot_arena_reserve_slots_grows_capacity() {
        let mut arena: SlotArena<i32> = SlotArena::new();
        let before = arena.capacity();
        arena.reserve_slots(32);
        assert!(arena.capacity() >= before + 32);
    }

    #[test]
    fn slot_arena_debug_snapshot() {
        let mut arena = SlotArena::new();
        let a = arena.insert("a");
        let b = arena.insert("b");
        arena.remove(a);
        let snapshot = arena.debug_snapshot();
        assert_eq!(snapshot.len, 1);
        assert!(snapshot.live_ids.contains(&b));
        assert!(snapshot.free_list.contains(&a.index()));
    }

    #[test]
    fn sharded_slot_arena_basic_ops() {
        let arena = ShardedSlotArena::new(2);
        let a = arena.insert(1);
        let b = arena.insert(2);
        assert!(arena.contains(a));
        assert!(arena.contains(b));
        assert_eq!(arena.get_with(a, |v| *v), Some(1));
        assert_eq!(arena.remove(b), Some(2));
        assert!(!arena.contains(b));
        assert_eq!(arena.len(), 1);
    }

    #[test]
    fn sharded_slot_arena_shard_for_key() {
        let arena: ShardedSlotArena<i32> = ShardedSlotArena::new(4);
        let shard = arena.shard_for_key(&"alpha");
        assert!(shard < arena.shard_count());
    }

    #[test]
    fn sharded_slot_arena_with_seed() {
        let arena: ShardedSlotArena<i32> = ShardedSlotArena::with_shards_seed(4, 0, 99);
        let shard = arena.shard_for_key(&"alpha");
        assert!(shard < arena.shard_count());
    }

    #[test]
    fn concurrent_slot_arena_try_ops() {
        let arena = ConcurrentSlotArena::new();
        let id = arena.insert(1);
        assert_eq!(arena.try_get_with(id, |v| *v), Some(1));
        arena.try_get_mut_with(id, |v| *v = 2);
        assert_eq!(arena.get_with(id, |v| *v), Some(2));
    }

    #[test]
    fn concurrent_slot_arena_clear_and_accessors() {
        let arena = ConcurrentSlotArena::new();
        let a = arena.insert(1);
        let b = arena.insert(2);
        assert_eq!(arena.get_with(a, |v| *v), Some(1));
        assert_eq!(arena.get_with(b, |v| *v), Some(2));

        arena.clear();
        assert!(arena.is_empty());
        assert!(!arena.contains(a));
        assert!(!arena.contains(b));
        assert_eq!(arena.get_with(a, |v| *v), None);
    }

    #[test]
    fn concurrent_slot_arena_get_mut_with_updates_value() {
        let arena = ConcurrentSlotArena::new();
        let id = arena.insert(5);
        arena.get_mut_with(id, |v| *v = 10);
        assert_eq!(arena.get_with(id, |v| *v), Some(10));
    }

    #[test]
    fn slot_arena_debug_invariants_hold() {
        let mut arena = SlotArena::new();
        let a = arena.insert(1);
        let b = arena.insert(2);
        arena.remove(a);
        let _ = arena.insert(3);
        assert!(arena.contains(b));
        arena.debug_validate_invariants();
    }
}