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
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(feature = "std")]
extern crate core;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use crate::{
registry,
Handle,
Registry,
};
use core::marker::PhantomData;
/// A strong handle to data registered in a specific [`StrongRegistry`].
///
/// Strong handles are useful for separating handles from different registries. A handle from one
/// strong registry cannot be used for a different strong registry because the handle type is
/// statically enforced at compile time.
pub trait StrongHandle: From<Handle> {
/// Returns the associated handle.
fn handle(&self) -> Handle;
}
/// The same as [`Registry<T>`], but with strongly-typed handles to prevent handles from being
/// shared across multiple registries.
///
/// The handle type must implement the [`StrongHandle`] trait.
pub struct StrongRegistry<H, T> {
registry: Registry<T>,
phantom_handle: PhantomData<H>,
}
impl<H, T> StrongRegistry<H, T>
where
H: StrongHandle,
{
/// Creates a new strong registry.
pub fn new() -> Self {
Self {
registry: Registry::new(),
phantom_handle: PhantomData,
}
}
/// Creates a new strong registry with the given capacity.
pub fn with_capacity(size: usize) -> Self {
Self {
registry: Registry::with_capacity(size),
phantom_handle: PhantomData,
}
}
/// Returns the number of elements owned by the strong registry.
pub fn len(&self) -> usize {
self.registry.len()
}
/// Registers a new value in the arena, returning a handle to that value.
pub fn register(&self, value: T) -> H {
H::from(self.registry.register(value))
}
/// Registers the contents of an iterator in the registry.
///
/// Returns a numeric range of handles `[a, b)`, where `a` is the handle of the first element
/// inserted and `b` is the handle after the last element inserted.
pub fn register_extend<I>(&self, iterable: I) -> (H, H)
where
I: IntoIterator<Item = T>,
{
let (a, b) = self.registry.register_extend(iterable);
(H::from(a), H::from(b))
}
/// Ensures there is enough continuous space for at least `additional` values.
pub fn reserve(&self, additional: usize) {
self.registry.reserve(additional)
}
/// Converts the [`StrongRegistry<T>`] into a [`Vec<T>`].
///
/// Items will maintain their handle as their vector index.
pub fn into_vec(self) -> Vec<T> {
self.registry.into_vec()
}
/// Returns an iterator that provides mutable access to all elements in the registry, in order
/// of registration.
///
/// Registries only allow mutable iteration because the entire registry must be borrowed for the
/// duration of the iteration. The mutable borrow to call this method allows Rust's borrow
/// checker to enforce this rule.
pub fn iter_mut(&mut self) -> registry::IterMut<T> {
self.registry.iter_mut()
}
/// Returns a mutable reference to a value previously registered in the strong registry.
pub fn get_mut(&self, handle: H) -> Option<&mut T> {
self.registry.get_mut(handle.handle())
}
/// Returns a reference to a value previously registered in the strong registry.
pub fn get(&self, handle: H) -> Option<&T> {
self.registry.get(handle.handle())
}
}
#[cfg(test)]
mod strong_registry_test {
use crate::{
Handle,
StrongHandle,
StrongRegistry,
};
use core::cell::Cell;
// A shared counter for how many times a value is deallocated.
struct DropCounter<'c>(&'c Cell<u32>);
impl<'c> Drop for DropCounter<'c> {
fn drop(&mut self) {
self.0.set(self.0.get() + 1);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct NodeHandle(Handle);
impl From<Handle> for NodeHandle {
fn from(value: Handle) -> Self {
Self(value)
}
}
impl StrongHandle for NodeHandle {
fn handle(&self) -> Handle {
self.0
}
}
// A node type, like one used in a list, tree, or graph data structure.
//
// Helps us verify that arena-allocated values can refer to each other.
struct Node<'d, T> {
parent: Option<NodeHandle>,
value: T,
#[allow(dead_code)]
drop_counter: DropCounter<'d>,
}
impl<'a, 'd, T> Node<'d, T> {
pub fn new(parent: Option<NodeHandle>, value: T, drop_counter: DropCounter<'d>) -> Self {
Self {
parent,
value,
drop_counter,
}
}
}
#[test]
fn works_exactly_like_registry() {
let drop_counter = Cell::new(0);
{
let registry = StrongRegistry::with_capacity(2);
// Allocate a chain of nodes that refer to each other.
let mut handle = registry.register(Node::new(None, 1, DropCounter(&drop_counter)));
assert_eq!(registry.len(), 1);
handle = registry.register(Node::new(Some(handle), 2, DropCounter(&drop_counter)));
assert_eq!(registry.len(), 2);
handle = registry.register(Node::new(Some(handle), 3, DropCounter(&drop_counter)));
assert_eq!(registry.len(), 3);
handle = registry.register(Node::new(Some(handle), 4, DropCounter(&drop_counter)));
assert_eq!(registry.len(), 4);
let mut node = registry.get(handle).unwrap();
assert_eq!(node.value, 4);
node = registry.get(node.parent.unwrap()).unwrap();
assert_eq!(node.value, 3);
node = registry.get(node.parent.unwrap()).unwrap();
assert_eq!(node.value, 2);
node = registry.get(node.parent.unwrap()).unwrap();
assert_eq!(node.value, 1);
assert_eq!(node.parent, None);
assert_eq!(drop_counter.get(), 0);
}
// All values deallocated at the same time.
assert_eq!(drop_counter.get(), 4);
}
}