e0/src/utils.rs

42 lines
834 B
Rust
Raw Normal View History

2022-07-18 02:00:19 +00:00
use std::collections::HashMap;
use std::hash::Hash;
2022-04-28 16:33:26 +00:00
2022-07-18 02:00:19 +00:00
pub struct LayeredEnv<K, V> {
parent: Option<Box<LayeredEnv<K, V>>>,
inner_map: HashMap<K, V>,
}
2022-04-28 16:33:26 +00:00
2022-07-18 02:00:19 +00:00
impl<K: Hash + Eq, V> LayeredEnv<K, V> {
2022-07-18 02:13:09 +00:00
pub fn new() -> Self {
LayeredEnv {
parent: None,
inner_map: HashMap::new(),
}
}
2022-07-18 02:00:19 +00:00
pub fn insert(&mut self, key: K, value: V) {
self.inner_map.insert(key, value);
}
pub fn push(self) -> LayeredEnv<K, V> {
LayeredEnv {
parent: Some(Box::new(self)),
inner_map: HashMap::new(),
}
}
pub fn pop(self) -> LayeredEnv<K, V> {
*self.parent.unwrap()
2022-04-28 16:33:26 +00:00
}
2022-07-18 02:00:19 +00:00
pub fn lookup(&self, key: &K) -> Option<&V> {
match self.inner_map.get(key) {
Some(v) => Some(v),
None => match self.parent.as_ref() {
Some(p) => p.lookup(key),
None => None,
},
}
2022-04-28 16:33:26 +00:00
}
}