use std::{any::Any, collections::HashMap, hash::Hash};
pub trait ErasedComponentChannel {
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
pub struct ComponentChannel<C> {
components: Vec<C>,
}
impl<C> ComponentChannel<C> {
pub fn new() -> Self {
let components = vec![];
Self { components }
}
pub fn new_box() -> Box<Self> {
let this = Self::new();
Box::new(this)
}
pub fn iter(&self) -> impl Iterator<Item = &C> {
self.components.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut C> {
self.components.iter_mut()
}
pub fn push(&mut self, component: C) {
self.components.push(component);
}
}
impl<C> ErasedComponentChannel for ComponentChannel<C>
where
C: 'static,
{
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
pub struct ComponentMap<K, C> {
components: HashMap<K, C>,
}
impl<K, C> ComponentMap<K, C>
where
K: Eq + Hash,
{
pub fn new() -> Self {
let components = HashMap::new();
Self { components }
}
pub fn new_box() -> Box<Self> {
let this = Self::new();
Box::new(this)
}
pub fn insert(&mut self, key: K, component: C) -> bool {
self.components
.insert(key, component)
.is_some()
}
pub fn get(&self, key: &K) -> Option<&C> {
self.components.get(key)
}
pub fn get_mut(&mut self, key: &K) -> Option<&mut C> {
self.components.get_mut(key)
}
pub fn iter(&self) -> impl Iterator<Item = (&K, &C)> {
self.components.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&K, &mut C)> {
self.components.iter_mut()
}
}
impl<K, C> ErasedComponentChannel for ComponentMap<K, C>
where
K: 'static,
C: 'static,
{
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}