| 1 |
//! The [`UniqueArena`] type and supporting definitions. |
| 2 |
|
| 3 |
use alloc::vec::Vec; |
| 4 |
use core::{fmt, hash, ops}; |
| 5 |
|
| 6 |
use super::handle::{BadHandle, Handle, Index}; |
| 7 |
use crate::{FastIndexSet, Span}; |
| 8 |
|
| 9 |
/// An arena whose elements are guaranteed to be unique. |
| 10 |
/// |
| 11 |
/// A `UniqueArena` holds a set of unique values of type `T`, each with an |
| 12 |
/// associated [`Span`]. Inserting a value returns a `Handle<T>`, which can be |
| 13 |
/// used to index the `UniqueArena` and obtain shared access to the `T` element. |
| 14 |
/// Access via a `Handle` is an array lookup - no hash lookup is necessary. |
| 15 |
/// |
| 16 |
/// The element type must implement `Eq` and `Hash`. Insertions of equivalent |
| 17 |
/// elements, according to `Eq`, all return the same `Handle`. |
| 18 |
/// |
| 19 |
/// Once inserted, elements generally may not be mutated, although a `replace` |
| 20 |
/// method exists to support rare cases. |
| 21 |
/// |
| 22 |
/// `UniqueArena` is similar to [`Arena`]: If `Arena` is vector-like, |
| 23 |
/// `UniqueArena` is `HashSet`-like. |
| 24 |
/// |
| 25 |
/// [`Arena`]: super::Arena |
| 26 |
#[derive(Clone)] |
| 27 |
pub struct UniqueArena<T> { |
| 28 |
set: FastIndexSet<T>, |
| 29 |
|
| 30 |
/// Spans for the elements, indexed by handle. |
| 31 |
/// |
| 32 |
/// The length of this vector is always equal to `set.len()`. `FastIndexSet` |
| 33 |
/// promises that its elements "are indexed in a compact range, without |
| 34 |
/// holes in the range 0..set.len()", so we can always use the indices |
| 35 |
/// returned by insertion as indices into this vector. |
| 36 |
span_info: Vec<Span>, |
| 37 |
} |
| 38 |
|
| 39 |
impl<T> UniqueArena<T> { |
| 40 |
/// Create a new arena with no initial capacity allocated. |
| 41 |
pub fn new() -> Self { |
| 42 |
UniqueArena { |
| 43 |
set: FastIndexSet::default(), |
| 44 |
span_info: Vec::new(), |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
/// Return the current number of items stored in this arena. |
| 49 |
pub fn len(&self) -> usize { |
| 50 |
self.set.len() |
| 51 |
} |
| 52 |
|
| 53 |
/// Return `true` if the arena contains no elements. |
| 54 |
pub fn is_empty(&self) -> bool { |
| 55 |
self.set.is_empty() |
| 56 |
} |
| 57 |
|
| 58 |
/// Clears the arena, keeping all allocations. |
| 59 |
pub fn clear(&mut self) { |
| 60 |
self.set.clear(); |
| 61 |
self.span_info.clear(); |
| 62 |
} |
| 63 |
|
| 64 |
/// Return the span associated with `handle`. |
| 65 |
/// |
| 66 |
/// If a value has been inserted multiple times, the span returned is the |
| 67 |
/// one provided with the first insertion. |
| 68 |
pub fn get_span(&self, handle: Handle<T>) -> Span { |
| 69 |
*self |
| 70 |
.span_info |
| 71 |
.get(handle.index()) |
| 72 |
.unwrap_or(&Span::default()) |
| 73 |
} |
| 74 |
|
| 75 |
#[cfg(feature = "compact")] |
| 76 |
pub(crate) fn drain_all(&mut self) -> UniqueArenaDrain<T> { |
| 77 |
UniqueArenaDrain { |
| 78 |
inner_elts: self.set.drain(..), |
| 79 |
inner_spans: self.span_info.drain(..), |
| 80 |
index: Index::new(0).unwrap(), |
| 81 |
} |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
#[cfg(feature = "compact")] |
| 86 |
pub struct UniqueArenaDrain<'a, T> { |
| 87 |
inner_elts: indexmap::set::Drain<'a, T>, |
| 88 |
inner_spans: alloc::vec::Drain<'a, Span>, |
| 89 |
index: Index, |
| 90 |
} |
| 91 |
|
| 92 |
#[cfg(feature = "compact")] |
| 93 |
impl<T> Iterator for UniqueArenaDrain<'_, T> { |
| 94 |
type Item = (Handle<T>, T, Span); |
| 95 |
|
| 96 |
fn next(&mut self) -> Option<Self::Item> { |
| 97 |
match self.inner_elts.next() { |
| 98 |
Some(elt) => { |
| 99 |
let handle = Handle::new(self.index); |
| 100 |
self.index = self.index.checked_add(1).unwrap(); |
| 101 |
let span = self.inner_spans.next().unwrap(); |
| 102 |
Some((handle, elt, span)) |
| 103 |
} |
| 104 |
None => None, |
| 105 |
} |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
impl<T: Eq + hash::Hash> UniqueArena<T> { |
| 110 |
/// Returns an iterator over the items stored in this arena, returning both |
| 111 |
/// the item's handle and a reference to it. |
| 112 |
pub fn iter(&self) -> impl DoubleEndedIterator<Item = (Handle<T>, &T)> + ExactSizeIterator { |
| 113 |
self.set.iter().enumerate().map(|(i, v)| { |
| 114 |
let index = unsafe { Index::new_unchecked(i as u32) }; |
| 115 |
(Handle::new(index), v) |
| 116 |
}) |
| 117 |
} |
| 118 |
|
| 119 |
/// Insert a new value into the arena. |
| 120 |
/// |
| 121 |
/// Return a [`Handle<T>`], which can be used to index this arena to get a |
| 122 |
/// shared reference to the element. |
| 123 |
/// |
| 124 |
/// If this arena already contains an element that is `Eq` to `value`, |
| 125 |
/// return a `Handle` to the existing element, and drop `value`. |
| 126 |
/// |
| 127 |
/// If `value` is inserted into the arena, associate `span` with |
| 128 |
/// it. An element's span can be retrieved with the [`get_span`] |
| 129 |
/// method. |
| 130 |
/// |
| 131 |
/// [`Handle<T>`]: Handle |
| 132 |
/// [`get_span`]: UniqueArena::get_span |
| 133 |
pub fn insert(&mut self, value: T, span: Span) -> Handle<T> { |
| 134 |
let (index, added) = self.set.insert_full(value); |
| 135 |
|
| 136 |
if added { |
| 137 |
debug_assert!(index == self.span_info.len()); |
| 138 |
self.span_info.push(span); |
| 139 |
} |
| 140 |
|
| 141 |
debug_assert!(self.set.len() == self.span_info.len()); |
| 142 |
|
| 143 |
Handle::from_usize(index) |
| 144 |
} |
| 145 |
|
| 146 |
/// Replace an old value with a new value. |
| 147 |
/// |
| 148 |
/// # Panics |
| 149 |
/// |
| 150 |
/// - if the old value is not in the arena |
| 151 |
/// - if the new value already exists in the arena |
| 152 |
pub fn replace(&mut self, old: Handle<T>, new: T) { |
| 153 |
let (index, added) = self.set.insert_full(new); |
| 154 |
assert!(added && index == self.set.len() - 1); |
| 155 |
|
| 156 |
self.set.swap_remove_index(old.index()).unwrap(); |
| 157 |
} |
| 158 |
|
| 159 |
/// Return this arena's handle for `value`, if present. |
| 160 |
/// |
| 161 |
/// If this arena already contains an element equal to `value`, |
| 162 |
/// return its handle. Otherwise, return `None`. |
| 163 |
pub fn get(&self, value: &T) -> Option<Handle<T>> { |
| 164 |
self.set |
| 165 |
.get_index_of(value) |
| 166 |
.map(|index| unsafe { Handle::from_usize_unchecked(index) }) |
| 167 |
} |
| 168 |
|
| 169 |
/// Return this arena's value at `handle`, if that is a valid handle. |
| 170 |
pub fn get_handle(&self, handle: Handle<T>) -> Result<&T, BadHandle> { |
| 171 |
self.set |
| 172 |
.get_index(handle.index()) |
| 173 |
.ok_or_else(|| BadHandle::new(handle)) |
| 174 |
} |
| 175 |
|
| 176 |
/// Assert that `handle` is valid for this arena. |
| 177 |
pub fn check_contains_handle(&self, handle: Handle<T>) -> Result<(), BadHandle> { |
| 178 |
if handle.index() < self.set.len() { |
| 179 |
Ok(()) |
| 180 |
} else { |
| 181 |
Err(BadHandle::new(handle)) |
| 182 |
} |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
impl<T> Default for UniqueArena<T> { |
| 187 |
fn default() -> Self { |
| 188 |
Self::new() |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
impl<T: fmt::Debug + Eq + hash::Hash> fmt::Debug for UniqueArena<T> { |
| 193 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 194 |
f.debug_map().entries(self.iter()).finish() |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
impl<T> ops::Index<Handle<T>> for UniqueArena<T> { |
| 199 |
type Output = T; |
| 200 |
fn index(&self, handle: Handle<T>) -> &T { |
| 201 |
&self.set[handle.index()] |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
#[cfg(feature = "serialize")] |
| 206 |
impl<T> serde::Serialize for UniqueArena<T> |
| 207 |
where |
| 208 |
T: Eq + hash::Hash + serde::Serialize, |
| 209 |
{ |
| 210 |
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 211 |
where |
| 212 |
S: serde::Serializer, |
| 213 |
{ |
| 214 |
self.set.serialize(serializer) |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
#[cfg(feature = "deserialize")] |
| 219 |
impl<'de, T> serde::Deserialize<'de> for UniqueArena<T> |
| 220 |
where |
| 221 |
T: Eq + hash::Hash + serde::Deserialize<'de>, |
| 222 |
{ |
| 223 |
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 224 |
where |
| 225 |
D: serde::Deserializer<'de>, |
| 226 |
{ |
| 227 |
let set = FastIndexSet::deserialize(deserializer)?; |
| 228 |
let span_info = core::iter::repeat_n(Span::default(), set.len()).collect(); |
| 229 |
|
| 230 |
Ok(Self { set, span_info }) |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
//Note: largely borrowed from `HashSet` implementation |
| 235 |
#[cfg(feature = "arbitrary")] |
| 236 |
impl<'a, T> arbitrary::Arbitrary<'a> for UniqueArena<T> |
| 237 |
where |
| 238 |
T: Eq + hash::Hash + arbitrary::Arbitrary<'a>, |
| 239 |
{ |
| 240 |
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { |
| 241 |
let mut arena = Self::default(); |
| 242 |
for elem in u.arbitrary_iter()? { |
| 243 |
arena.set.insert(elem?); |
| 244 |
arena.span_info.push(Span::UNDEFINED); |
| 245 |
} |
| 246 |
Ok(arena) |
| 247 |
} |
| 248 |
|
| 249 |
fn arbitrary_take_rest(u: arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { |
| 250 |
let mut arena = Self::default(); |
| 251 |
for elem in u.arbitrary_take_rest_iter()? { |
| 252 |
arena.set.insert(elem?); |
| 253 |
arena.span_info.push(Span::UNDEFINED); |
| 254 |
} |
| 255 |
Ok(arena) |
| 256 |
} |
| 257 |
|
| 258 |
#[inline] |
| 259 |
fn size_hint(depth: usize) -> (usize, Option<usize>) { |
| 260 |
let depth_hint = <usize as arbitrary::Arbitrary>::size_hint(depth); |
| 261 |
arbitrary::size_hint::and(depth_hint, (0, None)) |
| 262 |
} |
| 263 |
} |