use std::any::TypeId;
use std::collections::HashMap;
use crate::util::DbgTypeId;
use crate::Archetype;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Generation(u32);
#[derive(Default)]
pub struct Store {
vec: Vec<Generation>,
}
impl Store {
pub fn next(&mut self, id: usize) -> Generation {
if self.vec.len() <= id {
self.vec.resize(id + 1, Generation::default());
}
let generation = self.vec.get_mut(id).expect("just resized");
generation.0 = generation.0.wrapping_add(1);
*generation
}
pub fn get(&self, id: usize) -> Generation { self.vec.get(id).copied().unwrap_or_default() }
}
#[crate::global(dynec_as(crate))]
#[derive(Default)]
pub struct StoreMap {
map: HashMap<DbgTypeId, Store>,
}
impl StoreMap {
pub fn next<A: Archetype>(&mut self, id: usize) -> Generation {
self.map.entry(DbgTypeId::of::<A>()).or_default().next(id)
}
pub fn get<A: Archetype>(&self, id: usize) -> Generation {
match self.map.get(&TypeId::of::<A>()) {
Some(store) => store.get(id),
None => Generation::default(),
}
}
}
pub trait WeakStore {
fn resolve<A: Archetype>(&self) -> Option<&Store>;
}
impl WeakStore for Store {
fn resolve<A: Archetype>(&self) -> Option<&Store> { Some(self) }
}
impl WeakStore for StoreMap {
fn resolve<A: Archetype>(&self) -> Option<&Store> { self.map.get(&TypeId::of::<A>()) }
}