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<T> {
components: Vec<T>,
}
impl<T> ComponentChannel<T> {
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.components.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
self.components.iter_mut()
}
pub fn push(&mut self, component: T) {
self.components.push(component);
}
}
impl<T> ComponentChannel<T> {
pub fn new() -> Self {
let components = vec![];
Self { components }
}
pub fn new_box() -> Box<Self> {
let this = Self::new();
Box::new(this)
}
}
impl<T> ErasedComponentChannel for ComponentChannel<T>
where
T: 'static,
{
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
pub struct ComponentMap<TKey, TValue> {
components: HashMap<TKey, TValue>,
}
impl<TKey, TValue> ComponentMap<TKey, TValue>
where
TKey: 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: TKey, component: TValue) -> bool {
self.components
.insert(key, component)
.is_some()
}
pub fn get(&self, key: &TKey) -> Option<&TValue> {
self.components.get(key)
}
pub fn get_mut(&mut self, key: &TKey) -> Option<&mut TValue> {
self.components.get_mut(key)
}
pub fn iter(&self) -> impl Iterator<Item = (&TKey, &TValue)> {
self.components.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&TKey, &mut TValue)> {
self.components.iter_mut()
}
}
impl<TKey, TValue> ErasedComponentChannel for ComponentMap<TKey, TValue>
where
TKey: 'static,
TValue: 'static,
{
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}