Arena

Struct Arena 

Source
pub struct Arena<T> { /* private fields */ }
๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.
Expand description

An object arena.

Arena<T> holds an array of slots for storing objects. Every slot is always in one of two states: occupied or vacant.

Essentially, this is equivalent to Vec<Option<T>>.

ยงInsert and remove

When inserting a new object into arena, a vacant slot is found and then the object is placed into the slot. If there are no vacant slots, the array is reallocated with bigger capacity. The cost of insertion is amortized O(1).

When removing an object, the slot containing it is marked as vacant and the object is returned. The cost of removal is O(1).

use vec_arena::Arena;

let mut arena = Arena::new();
let a = arena.insert(10);
let b = arena.insert(20);

assert_eq!(a, 0); // 10 was placed at index 0
assert_eq!(b, 1); // 20 was placed at index 1

assert_eq!(arena.remove(a), Some(10));
assert_eq!(arena.get(a), None); // slot at index 0 is now vacant

assert_eq!(arena.insert(30), 0); // slot at index 0 is reused

ยงIndexing

You can also access objects in an arena by index, just like you would in a Vec. However, accessing a vacant slot by index or using an out-of-bounds index will result in panic.

use vec_arena::Arena;

let mut arena = Arena::new();
let a = arena.insert(10);
let b = arena.insert(20);

assert_eq!(arena[a], 10);
assert_eq!(arena[b], 20);

arena[a] += arena[b];
assert_eq!(arena[a], 30);

To access slots without fear of panicking, use get() and get_mut(), which return Options.

Implementationsยง

Sourceยง

impl<T> Arena<T>

Source

pub fn new() -> Self

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Constructs a new, empty arena.

The arena will not allocate until objects are inserted into it.

ยงExamples
use vec_arena::Arena;

let mut arena: Arena<i32> = Arena::new();
Examples found in repository?
examples/splay-tree.rs (line 44)
42    fn new() -> Splay<T> {
43        Splay {
44            arena: Arena::new(),
45            root: NULL,
46        }
47    }
More examples
Hide additional examples
examples/linked-list.rs (line 37)
35    fn new() -> Self {
36        List {
37            arena: Arena::new(),
38            head: NULL,
39            tail: NULL,
40        }
41    }
Source

pub fn with_capacity(cap: usize) -> Self

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Constructs a new, empty arena with the specified capacity (number of slots).

The arena will be able to hold exactly cap objects without reallocating. If cap is 0, the arena will not allocate.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::with_capacity(10);

assert_eq!(arena.len(), 0);
assert_eq!(arena.capacity(), 10);

// These inserts are done without reallocating...
for i in 0..10 {
    arena.insert(i);
}
assert_eq!(arena.capacity(), 10);

// ... but this one will reallocate.
arena.insert(11);
assert!(arena.capacity() > 10);
Source

pub fn capacity(&self) -> usize

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Returns the number of slots in the arena.

ยงExamples
use vec_arena::Arena;

let arena: Arena<i32> = Arena::with_capacity(10);
assert_eq!(arena.capacity(), 10);
Source

pub fn len(&self) -> usize

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Returns the number of occupied slots in the arena.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();
assert_eq!(arena.len(), 0);

for i in 0..10 {
    arena.insert(());
    assert_eq!(arena.len(), i + 1);
}
Examples found in repository?
examples/linked-list.rs (line 45)
44    fn len(&self) -> usize {
45        self.arena.len()
46    }
Source

pub fn is_empty(&self) -> bool

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Returns true if all slots are vacant.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();
assert!(arena.is_empty());

arena.insert(1);
assert!(!arena.is_empty());
Source

pub fn next_vacant(&self) -> usize

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Returns the index of the slot that next insert will use if no mutating calls take place in between.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();

let a = arena.next_vacant();
let b = arena.insert(1);
assert_eq!(a, b);
let c = arena.next_vacant();
let d = arena.insert(2);
assert_eq!(c, d);
Source

pub fn insert(&mut self, object: T) -> usize

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Inserts an object into the arena and returns the slot index it was stored in.

The arena will reallocate if itโ€™s full.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();

let a = arena.insert(1);
let b = arena.insert(2);
assert!(a != b);
Examples found in repository?
examples/linked-list.rs (lines 60-64)
59    fn push_back(&mut self, value: T) -> usize {
60        let node = self.arena.insert(Node {
61            prev: NULL,
62            next: NULL,
63            value: value,
64        });
65
66        let tail = self.tail;
67        self.link(tail, node);
68
69        self.tail = node;
70        if self.head == NULL {
71            self.head = node;
72        }
73        node
74    }
More examples
Hide additional examples
examples/splay-tree.rs (line 132)
126    fn insert(&mut self, value: T) {
127        // Variables:
128        // - `n` is the new node
129        // - `p` will be it's parent
130        // - `c` is the present child of `p`
131
132        let n = self.arena.insert(Node::new(value));
133
134        if self.root == NULL {
135            self.root = n;
136        } else {
137            let mut p = self.root;
138            loop {
139                // Decide whether to go left or right.
140                let dir = if self.arena[n].value < self.arena[p].value {
141                    0
142                } else {
143                    1
144                };
145                let c = self.arena[p].children[dir];
146
147                if c == NULL {
148                    self.link(p, n, dir);
149                    self.splay(n);
150                    break;
151                }
152                p = c;
153            }
154        }
155    }
Source

pub fn remove(&mut self, index: usize) -> Option<T>

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Removes the object stored at index from the arena and returns it.

If the slot is vacant or index is out of bounds, None will be returned.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();
let a = arena.insert("hello");

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

assert_eq!(arena.len(), 0);
assert_eq!(arena.remove(a), None);
Examples found in repository?
examples/linked-list.rs (line 78)
77    fn pop_front(&mut self) -> T {
78        let node = self.arena.remove(self.head).unwrap();
79
80        self.link(NULL, node.next);
81        self.head = node.next;
82        if node.next == NULL {
83            self.tail = NULL;
84        }
85        node.value
86    }
87
88    /// Removes the element specified by `index`.
89    fn remove(&mut self, index: usize) -> T {
90        let node = self.arena.remove(index).unwrap();
91
92        self.link(node.prev, node.next);
93        if self.head == index {
94            self.head = node.next;
95        }
96        if self.tail == index {
97            self.tail = node.prev;
98        }
99
100        node.value
101    }
Source

pub fn retain<F>(&mut self, f: F)
where F: FnMut(usize, &mut T) -> bool,

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Retains objects for which the closure returns true.

All other objects will be removed from the arena.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();

let a = arena.insert(0);
let b = arena.insert(1);
let c = arena.insert(2);

arena.retain(|k, v| k == a || *v == 1);

assert!(arena.get(a).is_some());
assert!(arena.get(b).is_some());
assert!(arena.get(c).is_none());
Source

pub fn clear(&mut self)

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Clears the arena, removing and dropping all objects it holds.

Keeps the allocated memory for reuse.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();
for i in 0..10 {
    arena.insert(i);
}

assert_eq!(arena.len(), 10);
arena.clear();
assert_eq!(arena.len(), 0);
Source

pub fn get(&self, index: usize) -> Option<&T>

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Returns a reference to the object stored at index.

If the slot is vacant or index is out of bounds, None will be returned.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();
let index = arena.insert("hello");

assert_eq!(arena.get(index), Some(&"hello"));
arena.remove(index);
assert_eq!(arena.get(index), None);
Source

pub fn get_mut(&mut self, index: usize) -> Option<&mut T>

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Returns a mutable reference to the object stored at index.

If the slot is vacant or index is out of bounds, None will be returned.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();
let index = arena.insert(7);

assert_eq!(arena.get_mut(index), Some(&mut 7));
*arena.get_mut(index).unwrap() *= 10;
assert_eq!(arena.get_mut(index), Some(&mut 70));
Source

pub fn swap(&mut self, a: usize, b: usize)

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Swaps two objects in the arena.

The two indices are a and b.

ยงPanics

Panics if any of the indices is out of bounds or any of the slots is vacant.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();
let a = arena.insert(7);
let b = arena.insert(8);

arena.swap(a, b);
assert_eq!(arena.get(a), Some(&8));
assert_eq!(arena.get(b), Some(&7));
Source

pub fn reserve(&mut self, additional: usize)

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Reserves capacity for at least additional more objects to be inserted.

The arena may reserve more space to avoid frequent reallocations.

ยงPanics

Panics if the new capacity overflows usize.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();
arena.insert("hello");

arena.reserve(10);
assert!(arena.capacity() >= 11);
Source

pub fn reserve_exact(&mut self, additional: usize)

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Reserves the minimum capacity for exactly additional more objects to be inserted.

Note that the allocator may give the arena more space than it requests.

ยงPanics

Panics if the new capacity overflows usize.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();
arena.insert("hello");

arena.reserve_exact(10);
assert!(arena.capacity() >= 11);
Source

pub fn iter(&self) -> Iter<'_, T> โ“˜

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Returns an iterator over occupied slots.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();
arena.insert(1);
arena.insert(2);
arena.insert(4);

let mut iterator = arena.iter();
assert_eq!(iterator.next(), Some((0, &1)));
assert_eq!(iterator.next(), Some((1, &2)));
assert_eq!(iterator.next(), Some((2, &4)));
Source

pub fn iter_mut(&mut self) -> IterMut<'_, T> โ“˜

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Returns an iterator that returns mutable references to objects.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::new();
arena.insert("zero".to_string());
arena.insert("one".to_string());
arena.insert("two".to_string());

for (index, object) in arena.iter_mut() {
    *object = index.to_string() + " " + object;
}

let mut iterator = arena.iter();
assert_eq!(iterator.next(), Some((0, &"0 zero".to_string())));
assert_eq!(iterator.next(), Some((1, &"1 one".to_string())));
assert_eq!(iterator.next(), Some((2, &"2 two".to_string())));
Source

pub fn shrink_to_fit(&mut self)

๐Ÿ‘ŽDeprecated since 1.2.0: This crate is now deprecated in favor of slab.

Shrinks the capacity of the arena as much as possible.

It will drop down as close as possible to the length but the allocator may still inform the arena that there is space for a few more elements.

ยงExamples
use vec_arena::Arena;

let mut arena = Arena::with_capacity(10);
arena.insert("first".to_string());
arena.insert("second".to_string());
arena.insert("third".to_string());
assert_eq!(arena.capacity(), 10);
arena.shrink_to_fit();
assert!(arena.capacity() >= 3);

Trait Implementationsยง

Sourceยง

impl<T: Clone> Clone for Arena<T>

Sourceยง

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 ยท Sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Sourceยง

impl<T> Debug for Arena<T>

Sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Sourceยง

impl<T> Default for Arena<T>

Sourceยง

fn default() -> Self

Returns the โ€œdefault valueโ€ for a type. Read more
Sourceยง

impl<T> FromIterator<T> for Arena<T>

Sourceยง

fn from_iter<U: IntoIterator<Item = T>>(iter: U) -> Arena<T>

Creates a value from an iterator. Read more
Sourceยง

impl<T> Index<usize> for Arena<T>

Sourceยง

type Output = T

The returned type after indexing.
Sourceยง

fn index(&self, index: usize) -> &T

Performs the indexing (container[index]) operation. Read more
Sourceยง

impl<T> IndexMut<usize> for Arena<T>

Sourceยง

fn index_mut(&mut self, index: usize) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more
Sourceยง

impl<'a, T> IntoIterator for &'a Arena<T>

Sourceยง

type Item = (usize, &'a T)

The type of the elements being iterated over.
Sourceยง

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
Sourceยง

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Sourceยง

impl<'a, T> IntoIterator for &'a mut Arena<T>

Sourceยง

type Item = (usize, &'a mut T)

The type of the elements being iterated over.
Sourceยง

type IntoIter = IterMut<'a, T>

Which kind of iterator are we turning this into?
Sourceยง

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Sourceยง

impl<T> IntoIterator for Arena<T>

Sourceยง

type Item = (usize, T)

The type of the elements being iterated over.
Sourceยง

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
Sourceยง

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementationsยง

ยง

impl<T> Freeze for Arena<T>

ยง

impl<T> RefUnwindSafe for Arena<T>
where T: RefUnwindSafe,

ยง

impl<T> Send for Arena<T>
where T: Send,

ยง

impl<T> Sync for Arena<T>
where T: Sync,

ยง

impl<T> Unpin for Arena<T>
where T: Unpin,

ยง

impl<T> UnwindSafe for Arena<T>
where T: UnwindSafe,

Blanket Implementationsยง

Sourceยง

impl<T> Any for T
where T: 'static + ?Sized,

Sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Sourceยง

impl<T> Borrow<T> for T
where T: ?Sized,

Sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Sourceยง

impl<T> BorrowMut<T> for T
where T: ?Sized,

Sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Sourceยง

impl<T> CloneToUninit for T
where T: Clone,

Sourceยง

unsafe fn clone_to_uninit(&self, dest: *mut u8)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Sourceยง

impl<T> From<T> for T

Sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

Sourceยง

impl<T, U> Into<U> for T
where U: From<T>,

Sourceยง

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Sourceยง

impl<T> ToOwned for T
where T: Clone,

Sourceยง

type Owned = T

The resulting type after obtaining ownership.
Sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Sourceยง

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
Sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Sourceยง

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.