use super::Resource;
use crate::prelude::*;
use alloc::collections::{BTreeMap, BTreeSet};
use core::any::Any;
use core::fmt;
use core::marker::PhantomData;
use core::mem;
use sealed::{DefaultTombstone, DeleteWithTombstone};
#[derive(Debug)]
pub enum ResourceTableError {
Full,
NotPresent,
WrongType,
HasChildren,
}
impl fmt::Display for ResourceTableError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Full => write!(f, "resource table has no free keys"),
Self::NotPresent => write!(f, "resource not present"),
Self::WrongType => write!(f, "resource is of another type"),
Self::HasChildren => write!(f, "resource has children"),
}
}
}
impl core::error::Error for ResourceTableError {}
pub struct ResourceTable<D: DeleteWithTombstone = DefaultTombstone> {
entries: Vec<Entry>,
free_head: Option<usize>,
free_count: usize,
max_capacity: usize,
live: usize,
_tombstone: PhantomData<D>,
}
#[derive(Debug)]
enum Entry {
Free { next: Option<usize> },
Occupied { entry: TableEntry },
}
impl Entry {
pub fn occupied(&self) -> Option<&TableEntry> {
match self {
Self::Occupied { entry } => Some(entry),
Self::Free { .. } => None,
}
}
pub fn occupied_mut(&mut self) -> Option<&mut TableEntry> {
match self {
Self::Occupied { entry } => Some(entry),
Self::Free { .. } => None,
}
}
}
struct Tombstone;
mod sealed {
pub trait DeleteWithTombstone {
const DELETE_WITH_TOMBSTONE: bool;
}
pub struct DefaultTombstone;
impl DeleteWithTombstone for DefaultTombstone {
const DELETE_WITH_TOMBSTONE: bool = false;
}
}
const DEFAULT_MAX_CAPACITY: usize = 1_000_000;
#[derive(Debug)]
struct TableEntry {
entry: Box<dyn Any + Send>,
parent: Option<u32>,
children: BTreeSet<u32>,
}
impl TableEntry {
fn new(entry: Box<dyn Any + Send>, parent: Option<u32>) -> Self {
Self {
entry,
parent,
children: BTreeSet::new(),
}
}
fn add_child(&mut self, child: u32) {
debug_assert!(!self.children.contains(&child));
self.children.insert(child);
}
fn remove_child(&mut self, child: u32) {
let was_removed = self.children.remove(&child);
debug_assert!(was_removed);
}
}
impl ResourceTable {
pub fn new() -> Self {
ResourceTable::with_capacity(0)
}
pub fn with_capacity(capacity: usize) -> Self {
ResourceTable::empty(capacity)
}
}
impl<D: DeleteWithTombstone> ResourceTable<D> {
fn empty(capacity: usize) -> Self {
ResourceTable {
entries: Vec::with_capacity(capacity),
free_head: None,
free_count: 0,
max_capacity: DEFAULT_MAX_CAPACITY,
live: 0,
_tombstone: PhantomData,
}
}
pub fn len(&self) -> usize {
self.live
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[cfg(any(feature = "component-model-async", test))]
pub(crate) fn ensure_capacity(&self, additional: usize) -> Result<(), ResourceTableError> {
let Some(to_append) = additional.checked_sub(self.free_count) else {
return Ok(());
};
if to_append > self.max_capacity.saturating_sub(self.entries.len()) {
Err(ResourceTableError::Full)
} else {
Ok(())
}
}
pub fn max_capacity(&self) -> usize {
self.max_capacity
}
pub fn set_max_capacity(&mut self, max: usize) {
self.max_capacity = max;
}
pub fn push<T>(&mut self, entry: T) -> Result<Resource<T>, ResourceTableError>
where
T: Send + 'static,
{
let idx = self.push_(TableEntry::new(Box::new(entry), None))?;
Ok(Resource::new_own(idx))
}
fn pop_free_list(&mut self) -> Option<usize> {
if let Some(ix) = self.free_head {
match &self.entries[ix] {
Entry::Free { next } => self.free_head = *next,
Entry::Occupied { .. } => unreachable!(),
}
self.free_count -= 1;
Some(ix)
} else {
None
}
}
#[inline]
fn free_entry(&mut self, ix: usize) -> TableEntry {
if D::DELETE_WITH_TOMBSTONE {
match mem::replace(
&mut self.entries[ix],
Entry::Occupied {
entry: TableEntry {
entry: Box::new(Tombstone),
parent: None,
children: BTreeSet::new(),
},
},
) {
Entry::Occupied { entry } => {
if !entry.entry.is::<Tombstone>() {
self.live -= 1;
}
entry
}
Entry::Free { .. } => unreachable!(),
}
} else {
let entry = match core::mem::replace(
&mut self.entries[ix],
Entry::Free {
next: self.free_head,
},
) {
Entry::Occupied { entry } => entry,
Entry::Free { .. } => unreachable!(),
};
self.free_head = Some(ix);
self.free_count += 1;
self.live -= 1;
entry
}
}
fn push_(&mut self, e: TableEntry) -> Result<u32, ResourceTableError> {
if let Some(free) = self.pop_free_list() {
self.entries[free] = Entry::Occupied { entry: e };
self.live += 1;
Ok(free.try_into().unwrap())
} else {
if self.entries.len() >= self.max_capacity {
return Err(ResourceTableError::Full);
}
let ix = self
.entries
.len()
.try_into()
.map_err(|_| ResourceTableError::Full)?;
self.entries.push(Entry::Occupied { entry: e });
self.live += 1;
Ok(ix)
}
}
fn occupied(&self, key: u32) -> Result<&TableEntry, ResourceTableError> {
self.entries
.get(key as usize)
.and_then(Entry::occupied)
.ok_or(ResourceTableError::NotPresent)
}
fn occupied_mut(&mut self, key: u32) -> Result<&mut TableEntry, ResourceTableError> {
self.entries
.get_mut(key as usize)
.and_then(Entry::occupied_mut)
.ok_or(ResourceTableError::NotPresent)
}
pub fn push_child<T, U>(
&mut self,
entry: T,
parent: &Resource<U>,
) -> Result<Resource<T>, ResourceTableError>
where
T: Send + 'static,
U: 'static,
{
let parent = parent.rep();
self.occupied(parent)?;
let child = self.push_(TableEntry::new(Box::new(entry), Some(parent)))?;
self.occupied_mut(parent)?.add_child(child);
Ok(Resource::new_own(child))
}
pub fn add_child<T: 'static, U: 'static>(
&mut self,
child: Resource<T>,
parent: Resource<U>,
) -> Result<(), ResourceTableError> {
let entry = self.occupied_mut(child.rep())?;
assert!(entry.parent.is_none());
entry.parent = Some(parent.rep());
self.occupied_mut(parent.rep())?.add_child(child.rep());
Ok(())
}
pub fn remove_child<T: 'static, U: 'static>(
&mut self,
child: Resource<T>,
parent: Resource<U>,
) -> Result<(), ResourceTableError> {
let entry = self.occupied_mut(child.rep())?;
assert_eq!(entry.parent, Some(parent.rep()));
entry.parent = None;
self.occupied_mut(parent.rep())?.remove_child(child.rep());
Ok(())
}
pub fn get<T: Any + Sized>(&self, key: &Resource<T>) -> Result<&T, ResourceTableError> {
self.get_(key.rep())?
.downcast_ref()
.ok_or(ResourceTableError::WrongType)
}
fn get_(&self, key: u32) -> Result<&dyn Any, ResourceTableError> {
let r = self.occupied(key)?;
Ok(&*r.entry)
}
pub fn get_mut<T: Any + Sized>(
&mut self,
key: &Resource<T>,
) -> Result<&mut T, ResourceTableError> {
self.get_any_mut(key.rep())?
.downcast_mut()
.ok_or(ResourceTableError::WrongType)
}
pub fn get_any_mut(&mut self, key: u32) -> Result<&mut dyn Any, ResourceTableError> {
let r = self.occupied_mut(key)?;
Ok(&mut *r.entry)
}
pub fn delete<T>(&mut self, resource: Resource<T>) -> Result<T, ResourceTableError>
where
T: Any,
{
debug_assert!(resource.owned());
let key = resource.rep();
if !self.occupied(key)?.children.is_empty() {
return Err(ResourceTableError::HasChildren);
}
let entry = self.free_entry(key as usize);
if let Some(parent) = entry.parent {
self.occupied_mut(parent)
.expect("missing parent")
.remove_child(key);
}
match entry.entry.downcast() {
Ok(t) => Ok(*t),
Err(_e) => Err(ResourceTableError::WrongType),
}
}
pub fn iter_entries<'a, T>(
&'a mut self,
map: BTreeMap<u32, T>,
) -> impl Iterator<Item = (Result<&'a mut dyn Any, ResourceTableError>, T)> {
map.into_iter().map(move |(k, v)| {
let item = self
.occupied_mut(k)
.map(|e| Box::as_mut(&mut e.entry))
.map(|item| unsafe { &mut *(item as *mut dyn Any) });
(item, v)
})
}
pub fn iter_children<T>(
&self,
parent: &Resource<T>,
) -> Result<impl Iterator<Item = &(dyn Any + Send)> + use<'_, T, D>, ResourceTableError>
where
T: 'static,
{
let parent_entry = self.occupied(parent.rep())?;
Ok(parent_entry.children.iter().map(|child_index| {
let child = self.occupied(*child_index).expect("missing child");
child.entry.as_ref()
}))
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (u32, &mut (dyn Any + Send))> {
self.entries
.iter_mut()
.enumerate()
.filter_map(|(rep, entry)| match entry {
Entry::Occupied { entry } => Some((u32::try_from(rep).unwrap(), &mut *entry.entry)),
Entry::Free { .. } => None,
})
}
}
impl Default for ResourceTable {
fn default() -> Self {
ResourceTable::new()
}
}
impl<D: DeleteWithTombstone> fmt::Debug for ResourceTable<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[")?;
let mut wrote = false;
for (index, entry) in self.entries.iter().enumerate() {
if let Entry::Occupied { entry } = entry {
if entry.entry.downcast_ref::<Tombstone>().is_none() {
if wrote {
write!(f, ", ")?;
} else {
wrote = true;
}
write!(f, "{index}")?;
}
}
}
write!(f, "]")
}
}
#[test]
pub fn test_free_list() {
let mut table = ResourceTable::new();
assert!(table.is_empty());
let x = table.push(()).unwrap();
assert_eq!(x.rep(), 0);
assert_eq!(table.len(), 1);
let y = table.push(()).unwrap();
assert_eq!(y.rep(), 1);
assert_eq!(table.len(), 2);
table.delete(x).unwrap();
assert_eq!(table.len(), 1);
let x = table.push(()).unwrap();
assert_eq!(x.rep(), 0);
assert_eq!(table.len(), 2);
table.delete(x).unwrap();
table.delete(y).unwrap();
let y = table.push(()).unwrap();
assert_eq!(y.rep(), 1);
let x = table.push(()).unwrap();
assert_eq!(x.rep(), 0);
let x = table.push(()).unwrap();
assert_eq!(x.rep(), 2);
assert_eq!(table.len(), 3);
}
#[test]
fn test_max_capacity() {
let mut table = ResourceTable::new();
assert_eq!(table.max_capacity(), DEFAULT_MAX_CAPACITY);
table.set_max_capacity(0);
assert_eq!(table.max_capacity(), 0);
assert!(table.push(()).is_err());
table.set_max_capacity(1);
assert_eq!(table.max_capacity(), 1);
let x = table.push(()).unwrap();
assert!(table.push(()).is_err());
assert_eq!(table.len(), 1);
table.set_max_capacity(0);
assert!(table.push(()).is_err());
table.delete(x).unwrap();
let x = table.push(()).unwrap();
table.delete(x).unwrap();
table.set_max_capacity(10);
let handles = (0..10).map(|_| table.push(()).unwrap()).collect::<Vec<_>>();
assert!(table.push(()).is_err());
for handle in handles {
table.delete(handle).unwrap();
}
assert!(table.is_empty());
table.push(()).unwrap();
}
#[test]
fn test_len_and_delete_errors() {
let mut table = ResourceTable::new();
let parent = table.push(()).unwrap();
let child = table.push_child(1u32, &parent).unwrap();
assert_eq!(table.len(), 2);
table.set_max_capacity(2);
assert!(matches!(
table.push_child(2u32, &parent),
Err(ResourceTableError::Full)
));
assert_eq!(table.len(), 2);
assert!(matches!(
table.delete(Resource::<()>::new_own(parent.rep())),
Err(ResourceTableError::HasChildren)
));
assert_eq!(table.len(), 2);
assert!(matches!(
table.push_child((), &Resource::<()>::new_own(100)),
Err(ResourceTableError::NotPresent)
));
assert_eq!(table.len(), 2);
assert!(matches!(
table.delete(Resource::<()>::new_own(child.rep())),
Err(ResourceTableError::WrongType)
));
assert_eq!(table.len(), 1);
assert!(matches!(
table.delete(Resource::<()>::new_own(100)),
Err(ResourceTableError::NotPresent)
));
assert_eq!(table.len(), 1);
table.delete(parent).unwrap();
assert!(table.is_empty());
}
#[test]
fn test_len_and_tombstones() {
struct DebugTombstone;
impl DeleteWithTombstone for DebugTombstone {
const DELETE_WITH_TOMBSTONE: bool = true;
}
let mut table = ResourceTable::<DebugTombstone>::empty(0);
table.set_max_capacity(1);
let value = table.push(1u32).unwrap();
let rep = value.rep();
table.delete(value).unwrap();
assert_eq!(table.len(), 0);
assert!(table.is_empty());
assert_eq!(table.entries.len(), 1);
assert!(matches!(
table.ensure_capacity(1),
Err(ResourceTableError::Full)
));
assert!(matches!(
table.delete(Resource::<u32>::new_own(rep)),
Err(ResourceTableError::WrongType)
));
assert_eq!(table.len(), 0);
assert!(table.is_empty());
}
#[test]
fn test_batch_capacity() {
let mut table = ResourceTable::new();
table.set_max_capacity(3);
table.ensure_capacity(0).unwrap();
table.ensure_capacity(3).unwrap();
assert!(matches!(
table.ensure_capacity(4),
Err(ResourceTableError::Full)
));
assert_eq!(table.entries.len(), 0);
let first = table.push(()).unwrap();
table.ensure_capacity(2).unwrap();
assert!(matches!(
table.ensure_capacity(3),
Err(ResourceTableError::Full)
));
table.delete(first).unwrap();
table.ensure_capacity(3).unwrap();
let handles = (0..3).map(|_| table.push(()).unwrap()).collect::<Vec<_>>();
for handle in handles {
table.delete(handle).unwrap();
}
table.set_max_capacity(0);
table.ensure_capacity(3).unwrap();
assert!(matches!(
table.ensure_capacity(4),
Err(ResourceTableError::Full)
));
assert_eq!(table.len(), 0);
assert_eq!(table.entries.len(), 3);
}