1use std::{borrow::Borrow, collections::HashMap, hash::Hash, rc::Rc};23#[derive(Default, Debug)]4struct LayeredHashMapInternals<K: Hash, V> {5 parent: Option<LayeredHashMap<K, V>>,6 current: HashMap<K, V>,7}89#[derive(Debug)]10pub struct LayeredHashMap<K: Hash, V>(Rc<LayeredHashMapInternals<K, V>>);1112impl<K: Hash + Eq, V> LayeredHashMap<K, V> {13 pub fn extend(&self, new_layer: HashMap<K, V>) -> Self {14 let super_map = self.clone();15 LayeredHashMap(Rc::new(LayeredHashMapInternals {16 parent: Some(super_map),17 current: new_layer,18 }))19 }2021 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>22 where23 K: Borrow<Q>,24 Q: Hash + Eq,25 {26 (self.0)27 .current28 .get(&key)29 .or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))30 }31}3233impl<K: Hash, V> Clone for LayeredHashMap<K, V> {34 fn clone(&self) -> Self {35 LayeredHashMap(self.0.clone())36 }37}3839impl<K: Hash + Eq, V> Default for LayeredHashMap<K, V> {40 fn default() -> Self {41 LayeredHashMap(Rc::new(LayeredHashMapInternals {42 parent: None,43 current: HashMap::new(),44 }))45 }46}