lavina/src/util/table.rs

82 lines
1.9 KiB
Rust
Raw Normal View History

2023-02-03 22:43:59 +00:00
use std::collections::HashMap;
2023-02-04 01:01:49 +00:00
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
2023-02-03 22:43:59 +00:00
pub struct Key(u32);
2023-02-04 01:01:49 +00:00
/// Hash map with auto-generated surrogate key.
2023-02-03 22:43:59 +00:00
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(),
}
}
2023-02-04 01:01:49 +00:00
/// Generate a free key and insert a table under that key.
pub fn insert(&mut self, value: V) -> Key {
2023-02-03 22:43:59 +00:00
let id = self.next;
self.next += 1;
2023-02-04 01:01:49 +00:00
self.inner.insert(id, value); // should be always empty
Key(id)
2023-02-03 22:43:59 +00:00
}
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))
}
}