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 #[inline(always)]22 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>23 where24 K: Borrow<Q>,25 Q: Hash + Eq,26 {27 (self.0)28 .current29 .get(&key)30 .or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))31 }32}3334impl<K: Hash, V> Clone for LayeredHashMap<K, V> {35 fn clone(&self) -> Self {36 LayeredHashMap(self.0.clone())37 }38}3940impl<K: Hash + Eq, V> Default for LayeredHashMap<K, V> {41 fn default() -> Self {42 LayeredHashMap(Rc::new(LayeredHashMapInternals {43 parent: None,44 current: HashMap::new(),45 }))46 }47}