forked from lavina/lavina
78 lines
1.7 KiB
Rust
78 lines
1.7 KiB
Rust
|
use std::collections::HashMap;
|
||
|
|
||
|
pub struct Key(u32);
|
||
|
|
||
|
pub struct AnonTable<V> {
|
||
|
next: u32,
|
||
|
inner: HashMap<u32, V>,
|
||
|
}
|
||
|
|
||
|
impl<V> AnonTable<V> {
|
||
|
pub fn new() -> AnonTable<V> {
|
||
|
AnonTable {
|
||
|
next: 0,
|
||
|
inner: HashMap::new(),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub fn insert(&mut self, value: V) -> Option<V> {
|
||
|
let id = self.next;
|
||
|
self.next += 1;
|
||
|
self.inner.insert(id, value)
|
||
|
}
|
||
|
|
||
|
pub fn get_mut(&mut self, key: Key) -> Option<&mut V> {
|
||
|
self.inner.get_mut(&key.0)
|
||
|
}
|
||
|
|
||
|
pub fn get(&self, key: Key) -> Option<&V> {
|
||
|
self.inner.get(&key.0)
|
||
|
}
|
||
|
|
||
|
pub fn pop(&mut self, key: Key) -> Option<V> {
|
||
|
self.inner.remove(&key.0)
|
||
|
}
|
||
|
|
||
|
pub fn len(&self) -> usize {
|
||
|
self.inner.len()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub struct AnonTableIterator<'a, V>(<&'a HashMap<u32, V> as IntoIterator>::IntoIter);
|
||
|
impl<'a, V> Iterator for AnonTableIterator<'a, V> {
|
||
|
type Item = &'a V;
|
||
|
|
||
|
fn next(&mut self) -> Option<&'a V> {
|
||
|
self.0.next().map(|a| a.1)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl<'a, V> IntoIterator for &'a AnonTable<V> {
|
||
|
type Item = &'a V;
|
||
|
|
||
|
type IntoIter = AnonTableIterator<'a, V>;
|
||
|
|
||
|
fn into_iter(self) -> Self::IntoIter {
|
||
|
AnonTableIterator(IntoIterator::into_iter(&self.inner))
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub struct AnonTableMutIterator<'a, V>(<&'a mut HashMap<u32, V> as IntoIterator>::IntoIter);
|
||
|
impl<'a, V> Iterator for AnonTableMutIterator<'a, V> {
|
||
|
type Item = &'a mut V;
|
||
|
|
||
|
fn next(&mut self) -> Option<&'a mut V> {
|
||
|
self.0.next().map(|a| a.1)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl<'a, V> IntoIterator for &'a mut AnonTable<V> {
|
||
|
type Item = &'a mut V;
|
||
|
|
||
|
type IntoIter = AnonTableMutIterator<'a, V>;
|
||
|
|
||
|
fn into_iter(self) -> Self::IntoIter {
|
||
|
AnonTableMutIterator(IntoIterator::into_iter(&mut self.inner))
|
||
|
}
|
||
|
}
|