use core::hash::Hash;
use std::{collections::HashMap, marker::PhantomData};
#[derive(Debug)]
pub struct Handle<V> {
handle: usize,
marker: PhantomData<V>,
}
impl<V> Handle<V> {
fn new(handle: usize) -> Self {
Self {
handle,
marker: PhantomData,
}
}
}
impl<V> PartialEq for Handle<V> {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
impl<V> Eq for Handle<V> {}
impl<V> Hash for Handle<V> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
state.write_usize(self.handle)
}
}
impl<V> Clone for Handle<V> {
fn clone(&self) -> Self {
Handle::new(self.handle)
}
}
impl<V> Copy for Handle<V> {}
#[derive(Debug)]
pub struct HandleMap<V> {
storage: HashMap<Handle<V>, V>,
}
impl<V> HandleMap<V> {
pub fn new() -> Self {
Self {
storage: HashMap::new(),
}
}
pub fn insert(&mut self, value: V) -> Handle<V> {
self.register(value)
}
pub fn get(&self, handle: Handle<V>) -> Option<&V> {
self.storage.get(&handle)
}
pub fn get_mut(&mut self, handle: Handle<V>) -> Option<&mut V> {
self.storage.get_mut(&handle)
}
pub fn remove(&mut self, handle: Handle<V>) -> Option<V> {
self.storage.remove(&handle)
}
fn register(&mut self, value: V) -> Handle<V> {
let id = self.storage.len();
let handle = Handle::new(id);
self.storage.insert(handle, value);
handle
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn insert_and_retrieve() {
let mut map: HandleMap<String> = HandleMap::new();
let hello = "Hello".to_string();
let handle_1 = map.insert(hello.clone());
let _ = map.insert("World".to_string());
let res = map.get(handle_1);
assert!(res.is_some());
assert_eq!(&hello, res.unwrap());
}
#[test]
fn get_missing() {
let mut map: HandleMap<String> = HandleMap::new();
let hello = "Hello".to_string();
let handle_1 = map.insert(hello.clone());
map.remove(handle_1);
let res = map.get(handle_1);
assert!(res.is_none());
}
}