use std::fmt::{Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
#[repr(transparent)]
pub struct Key<Tag: ?Sized> {
index: usize,
_phantom: PhantomData<Tag>,
}
impl<Tag: ?Sized> Key<Tag> {
pub fn from_raw(index: usize) -> Self {
Key {
index,
_phantom: PhantomData,
}
}
}
impl<Tag: ?Sized> Clone for Key<Tag> {
fn clone(&self) -> Self {
*self
}
}
impl<Tag: ?Sized> Copy for Key<Tag> {}
impl<Tag: ?Sized> PartialEq for Key<Tag> {
fn eq(&self, other: &Self) -> bool {
self.index == other.index
}
}
impl<Tag: ?Sized> Eq for Key<Tag> {}
impl<Tag: ?Sized> Hash for Key<Tag> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.index.hash(state);
}
}
impl<Tag: ?Sized> Debug for Key<Tag> {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
write!(f, "Key({})", self.index)
}
}
impl<Tag: ?Sized> Display for Key<Tag> {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
write!(f, "{}", self.index)
}
}
#[repr(transparent)]
pub struct SlotVec<Tag: ?Sized, Val> {
slots: Vec<Val>,
_phantom: PhantomData<Tag>,
}
impl<Tag: ?Sized, Val> SlotVec<Tag, Val> {
pub fn new() -> Self {
Self {
slots: Vec::default(),
_phantom: PhantomData,
}
}
pub fn insert(&mut self, value: Val) -> Key<Tag> {
let key = Key::from_raw(self.slots.len());
self.slots.push(value);
key
}
pub fn insert_with_key<F>(&mut self, func: F) -> Key<Tag>
where
F: FnOnce(Key<Tag>) -> Val,
{
let key = Key::from_raw(self.slots.len());
self.slots.push((func)(key));
key
}
pub fn get(&self, key: Key<Tag>) -> Option<&Val> {
self.slots.get(key.index)
}
pub fn get_mut(&mut self, key: Key<Tag>) -> Option<&mut Val> {
self.slots.get_mut(key.index)
}
pub fn len(&self) -> usize {
self.slots.len()
}
pub fn is_empty(&self) -> bool {
self.slots.is_empty()
}
}
impl<Tag: ?Sized, Val> Index<Key<Tag>> for SlotVec<Tag, Val> {
type Output = Val;
fn index(&self, key: Key<Tag>) -> &Self::Output {
self.get(key).unwrap()
}
}
impl<Tag: ?Sized, Val> IndexMut<Key<Tag>> for SlotVec<Tag, Val> {
fn index_mut(&mut self, key: Key<Tag>) -> &mut Self::Output {
self.get_mut(key).unwrap()
}
}
impl<Key: ?Sized, Val> Default for SlotVec<Key, Val> {
fn default() -> Self {
Self::new()
}
}