rust/lib/la-arena/src/lib.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

366 lines
9.1 KiB
Rust
Raw Normal View History

//! Yet another index-based arena.
2021-01-14 17:37:09 -06:00
#![warn(missing_docs)]
2019-01-04 07:01:06 -06:00
use std::{
fmt,
2020-03-19 10:00:11 -05:00
hash::{Hash, Hasher},
iter::FromIterator,
2019-01-04 07:01:06 -06:00
marker::PhantomData,
2021-10-04 22:10:25 -05:00
ops::{Index, IndexMut, Range, RangeInclusive},
2019-01-04 07:01:06 -06:00
};
mod map;
pub use map::ArenaMap;
2019-01-06 16:57:39 -06:00
/// The raw index of a value in an arena.
2019-01-04 07:01:06 -06:00
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RawIdx(u32);
2019-01-04 07:01:06 -06:00
impl From<RawIdx> for u32 {
fn from(raw: RawIdx) -> u32 {
2019-01-04 07:01:06 -06:00
raw.0
}
}
impl From<u32> for RawIdx {
fn from(idx: u32) -> RawIdx {
RawIdx(idx)
2019-01-04 07:01:06 -06:00
}
}
impl fmt::Debug for RawIdx {
2019-01-04 07:01:06 -06:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Display for RawIdx {
2019-01-04 07:01:06 -06:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
/// The index of a value allocated in an arena that holds `T`s.
2020-03-19 10:00:11 -05:00
pub struct Idx<T> {
raw: RawIdx,
2020-03-19 10:00:11 -05:00
_ty: PhantomData<fn() -> T>,
2019-01-04 07:01:06 -06:00
}
2020-03-19 10:00:11 -05:00
impl<T> Clone for Idx<T> {
fn clone(&self) -> Self {
*self
2019-01-10 13:47:05 -06:00
}
}
2020-03-19 10:00:11 -05:00
impl<T> Copy for Idx<T> {}
2019-01-10 13:47:05 -06:00
2020-03-19 10:00:11 -05:00
impl<T> PartialEq for Idx<T> {
fn eq(&self, other: &Idx<T>) -> bool {
self.raw == other.raw
}
}
impl<T> Eq for Idx<T> {}
impl<T> Hash for Idx<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.raw.hash(state);
2020-03-19 10:00:11 -05:00
}
}
impl<T> fmt::Debug for Idx<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut type_name = std::any::type_name::<T>();
if let Some(idx) = type_name.rfind(':') {
type_name = &type_name[idx + 1..];
2019-01-04 07:01:06 -06:00
}
2020-03-19 10:00:11 -05:00
write!(f, "Idx::<{}>({})", type_name, self.raw)
}
2019-01-04 07:01:06 -06:00
}
2020-03-19 10:00:11 -05:00
impl<T> Idx<T> {
/// Creates a new index from a [`RawIdx`].
pub fn from_raw(raw: RawIdx) -> Self {
2020-03-19 10:00:11 -05:00
Idx { raw, _ty: PhantomData }
}
2021-01-14 17:37:09 -06:00
/// Converts this index into the underlying [`RawIdx`].
pub fn into_raw(self) -> RawIdx {
2020-03-19 10:00:11 -05:00
self.raw
}
}
2021-10-04 22:10:25 -05:00
/// A range of densely allocated arena values.
pub struct IdxRange<T> {
range: Range<u32>,
_p: PhantomData<T>,
}
impl<T> IdxRange<T> {
/// Creates a new index range
/// inclusive of the start value and exclusive of the end value.
///
/// ```
/// let mut arena = la_arena::Arena::new();
/// let a = arena.alloc("a");
/// let b = arena.alloc("b");
/// let c = arena.alloc("c");
/// let d = arena.alloc("d");
///
/// let range = la_arena::IdxRange::new(b..d);
/// assert_eq!(&arena[range], &["b", "c"]);
/// ```
pub fn new(range: Range<Idx<T>>) -> Self {
Self { range: range.start.into_raw().into()..range.end.into_raw().into(), _p: PhantomData }
}
/// Creates a new index range
/// inclusive of the start value and end value.
///
/// ```
/// let mut arena = la_arena::Arena::new();
/// let foo = arena.alloc("foo");
/// let bar = arena.alloc("bar");
/// let baz = arena.alloc("baz");
///
/// let range = la_arena::IdxRange::new_inclusive(foo..=baz);
/// assert_eq!(&arena[range], &["foo", "bar", "baz"]);
///
/// let range = la_arena::IdxRange::new_inclusive(foo..=foo);
/// assert_eq!(&arena[range], &["foo"]);
/// ```
pub fn new_inclusive(range: RangeInclusive<Idx<T>>) -> Self {
Self {
range: u32::from(range.start().into_raw())..u32::from(range.end().into_raw()) + 1,
_p: PhantomData,
}
}
/// Returns whether the index range is empty.
///
/// ```
/// let mut arena = la_arena::Arena::new();
/// let one = arena.alloc(1);
/// let two = arena.alloc(2);
///
/// assert!(la_arena::IdxRange::new(one..one).is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.range.is_empty()
}
}
impl<T> Iterator for IdxRange<T> {
type Item = Idx<T>;
fn next(&mut self) -> Option<Self::Item> {
self.range.next().map(|raw| Idx::from_raw(raw.into()))
}
}
impl<T> DoubleEndedIterator for IdxRange<T> {
fn next_back(&mut self) -> Option<Self::Item> {
self.range.next_back().map(|raw| Idx::from_raw(raw.into()))
}
}
impl<T> fmt::Debug for IdxRange<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple(&format!("IdxRange::<{}>", std::any::type_name::<T>()))
.field(&self.range)
.finish()
}
}
impl<T> Clone for IdxRange<T> {
fn clone(&self) -> Self {
Self { range: self.range.clone(), _p: PhantomData }
}
}
impl<T> PartialEq for IdxRange<T> {
fn eq(&self, other: &Self) -> bool {
self.range == other.range
}
}
impl<T> Eq for IdxRange<T> {}
/// Yet another index-based arena.
#[derive(Clone, PartialEq, Eq, Hash)]
2020-03-19 10:00:11 -05:00
pub struct Arena<T> {
data: Vec<T>,
2019-01-04 07:01:06 -06:00
}
2020-03-19 10:00:11 -05:00
impl<T: fmt::Debug> fmt::Debug for Arena<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Arena").field("len", &self.len()).field("data", &self.data).finish()
2019-11-24 13:44:24 -06:00
}
}
2020-03-19 10:00:11 -05:00
impl<T> Arena<T> {
2021-01-14 17:37:09 -06:00
/// Creates a new empty arena.
///
/// ```
/// let arena: la_arena::Arena<i32> = la_arena::Arena::new();
/// assert!(arena.is_empty());
/// ```
2020-03-19 10:00:11 -05:00
pub const fn new() -> Arena<T> {
Arena { data: Vec::new() }
}
2021-01-14 17:37:09 -06:00
/// Empties the arena, removing all contained values.
///
/// ```
/// let mut arena = la_arena::Arena::new();
///
/// arena.alloc(1);
/// arena.alloc(2);
/// arena.alloc(3);
/// assert_eq!(arena.len(), 3);
///
/// arena.clear();
/// assert!(arena.is_empty());
/// ```
pub fn clear(&mut self) {
self.data.clear();
}
2020-03-19 10:00:11 -05:00
2021-01-14 17:37:09 -06:00
/// Returns the length of the arena.
///
/// ```
/// let mut arena = la_arena::Arena::new();
/// assert_eq!(arena.len(), 0);
///
/// arena.alloc("foo");
/// assert_eq!(arena.len(), 1);
///
/// arena.alloc("bar");
/// assert_eq!(arena.len(), 2);
///
/// arena.alloc("baz");
/// assert_eq!(arena.len(), 3);
/// ```
2019-01-08 06:53:32 -06:00
pub fn len(&self) -> usize {
self.data.len()
}
2021-01-14 17:37:09 -06:00
/// Returns whether the arena contains no elements.
///
/// ```
/// let mut arena = la_arena::Arena::new();
/// assert!(arena.is_empty());
///
/// arena.alloc(0.5);
/// assert!(!arena.is_empty());
/// ```
2019-04-26 10:42:10 -05:00
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
2021-01-14 17:37:09 -06:00
/// Allocates a new value on the arena, returning the values index.
2021-01-14 17:37:09 -06:00
///
/// ```
/// let mut arena = la_arena::Arena::new();
/// let idx = arena.alloc(50);
2021-01-14 17:37:09 -06:00
///
/// assert_eq!(arena[idx], 50);
2021-01-14 17:37:09 -06:00
/// ```
2020-03-19 10:00:11 -05:00
pub fn alloc(&mut self, value: T) -> Idx<T> {
2021-10-04 22:10:25 -05:00
let idx = self.next_idx();
2019-01-04 07:01:06 -06:00
self.data.push(value);
2021-10-04 22:10:25 -05:00
idx
2019-01-04 07:01:06 -06:00
}
2021-01-14 17:37:09 -06:00
/// Returns an iterator over the arenas elements.
///
/// ```
/// let mut arena = la_arena::Arena::new();
/// let idx1 = arena.alloc(20);
/// let idx2 = arena.alloc(40);
/// let idx3 = arena.alloc(60);
2021-01-14 17:37:09 -06:00
///
/// let mut iterator = arena.iter();
/// assert_eq!(iterator.next(), Some((idx1, &20)));
/// assert_eq!(iterator.next(), Some((idx2, &40)));
/// assert_eq!(iterator.next(), Some((idx3, &60)));
2021-01-14 17:37:09 -06:00
/// ```
2020-03-19 10:00:11 -05:00
pub fn iter(
&self,
) -> impl Iterator<Item = (Idx<T>, &T)> + ExactSizeIterator + DoubleEndedIterator {
self.data.iter().enumerate().map(|(idx, value)| (Idx::from_raw(RawIdx(idx as u32)), value))
2019-01-04 07:01:06 -06:00
}
2021-01-14 17:37:09 -06:00
/// Returns an iterator over the arenas mutable elements.
///
/// ```
/// let mut arena = la_arena::Arena::new();
/// let idx1 = arena.alloc(20);
///
/// assert_eq!(arena[idx1], 20);
///
/// let mut iterator = arena.iter_mut();
/// *iterator.next().unwrap().1 = 10;
/// drop(iterator);
///
/// assert_eq!(arena[idx1], 10);
/// ```
pub fn iter_mut(
&mut self,
) -> impl Iterator<Item = (Idx<T>, &mut T)> + ExactSizeIterator + DoubleEndedIterator {
self.data
.iter_mut()
.enumerate()
.map(|(idx, value)| (Idx::from_raw(RawIdx(idx as u32)), value))
}
2021-01-14 17:37:09 -06:00
/// Reallocates the arena to make it take up as little space as possible.
2020-06-24 09:14:58 -05:00
pub fn shrink_to_fit(&mut self) {
self.data.shrink_to_fit();
}
2021-10-04 22:10:25 -05:00
/// Returns the index of the next value allocated on the arena.
///
/// This method should remain private to make creating invalid `Idx`s harder.
fn next_idx(&self) -> Idx<T> {
Idx::from_raw(RawIdx(self.data.len() as u32))
}
2019-01-04 07:01:06 -06:00
}
2020-03-19 10:00:11 -05:00
impl<T> Default for Arena<T> {
fn default() -> Arena<T> {
Arena { data: Vec::new() }
2019-01-04 07:01:06 -06:00
}
}
2020-03-19 10:00:11 -05:00
impl<T> Index<Idx<T>> for Arena<T> {
2019-01-04 07:01:06 -06:00
type Output = T;
2020-03-19 10:00:11 -05:00
fn index(&self, idx: Idx<T>) -> &T {
2019-01-04 07:01:06 -06:00
let idx = idx.into_raw().0 as usize;
&self.data[idx]
}
}
2020-03-19 10:00:11 -05:00
impl<T> IndexMut<Idx<T>> for Arena<T> {
fn index_mut(&mut self, idx: Idx<T>) -> &mut T {
2019-01-04 07:01:06 -06:00
let idx = idx.into_raw().0 as usize;
&mut self.data[idx]
}
}
2019-01-25 05:21:14 -06:00
2021-10-04 22:10:25 -05:00
impl<T> Index<IdxRange<T>> for Arena<T> {
type Output = [T];
fn index(&self, range: IdxRange<T>) -> &[T] {
let start = range.range.start as usize;
let end = range.range.end as usize;
&self.data[start..end]
}
}
2020-03-19 10:00:11 -05:00
impl<T> FromIterator<T> for Arena<T> {
2019-01-25 05:21:14 -06:00
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = T>,
{
2020-03-19 10:00:11 -05:00
Arena { data: Vec::from_iter(iter) }
2019-01-25 05:21:14 -06:00
}
}