use super::SlotId;
#[derive(Clone, Debug)]
pub(crate) struct EntryArena<T> {
slots: Vec<Option<T>>,
free_slots: Vec<usize>,
len: usize,
}
impl<T> EntryArena<T> {
#[must_use]
#[inline]
pub(crate) const fn new() -> Self {
Self {
slots: Vec::new(),
free_slots: Vec::new(),
len: 0,
}
}
#[must_use]
#[inline]
pub(crate) fn with_capacity(capacity: usize) -> Self {
Self {
slots: Vec::with_capacity(capacity),
free_slots: Vec::new(),
len: 0,
}
}
#[must_use]
#[inline]
pub(crate) const fn len(&self) -> usize {
self.len
}
#[must_use]
#[inline]
pub(crate) fn capacity(&self) -> usize {
self.slots.capacity()
}
#[inline]
pub(crate) fn get(&self, id: SlotId) -> Option<&T> {
self.slots[id.0].as_ref()
}
#[inline]
pub(crate) fn get_mut(&mut self, id: SlotId) -> Option<&mut T> {
self.slots[id.0].as_mut()
}
#[inline]
pub(crate) fn reserve(&mut self, additional: usize) {
if additional > self.free_slots.len() {
self.slots.reserve(additional - self.free_slots.len());
}
}
#[must_use]
pub(crate) fn insert(&mut self, value: T) -> SlotId {
let slot = if let Some(slot) = self.free_slots.pop() {
assert!(self.slots[slot].is_none(), "free arena slot must be vacant");
self.slots[slot] = Some(value);
slot
} else {
let slot = self.slots.len();
self.slots.push(Some(value));
slot
};
self.len += 1;
SlotId(slot)
}
pub(crate) fn remove(&mut self, id: SlotId) -> Option<T> {
let value = self.slots[id.0].take()?;
self.free_slots.push(id.0);
self.len -= 1;
Some(value)
}
#[inline]
pub(crate) fn clear(&mut self) {
self.slots.clear();
self.free_slots.clear();
self.len = 0;
}
}