1use rustc_hash::FxHashMap;2use std::{borrow::Borrow, hash::Hash, rc::Rc};34#[derive(Default, Debug)]5struct LayeredHashMapInternals<K: Hash, V> {6 parent: Option<LayeredHashMap<K, V>>,7 current: FxHashMap<K, V>,8}910#[derive(Debug)]11pub struct LayeredHashMap<K: Hash, V>(Rc<LayeredHashMapInternals<K, V>>);1213impl<K: Hash + Eq, V> LayeredHashMap<K, V> {14 pub fn extend(self, new_layer: FxHashMap<K, V>) -> Self {15 match Rc::try_unwrap(self.0) {16 Ok(mut map) => {17 map.current.extend(new_layer);18 Self(Rc::new(map))19 }20 Err(this) => Self(Rc::new(LayeredHashMapInternals {21 parent: Some(Self(this)),22 current: new_layer,23 })),24 }25 }2627 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>28 where29 K: Borrow<Q>,30 Q: Hash + Eq,31 {32 (self.0)33 .current34 .get(key)35 .or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))36 }37}3839impl<K: Hash, V> Clone for LayeredHashMap<K, V> {40 fn clone(&self) -> Self {41 Self(self.0.clone())42 }43}4445impl<K: Hash + Eq, V> Default for LayeredHashMap<K, V> {46 fn default() -> Self {47 Self(Rc::new(LayeredHashMapInternals {48 parent: None,49 current: FxHashMap::default(),50 }))51 }52}