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 match Rc::try_unwrap(self.0) {15 Ok(mut map) => {16 map.current.extend(new_layer);17 LayeredHashMap(Rc::new(map))18 }19 Err(this) => LayeredHashMap(Rc::new(LayeredHashMapInternals {20 parent: Some(LayeredHashMap(this)),21 current: new_layer,22 })),23 }24 }2526 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>27 where28 K: Borrow<Q>,29 Q: Hash + Eq,30 {31 (self.0)32 .current33 .get(&key)34 .or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))35 }36}3738impl<K: Hash, V> Clone for LayeredHashMap<K, V> {39 fn clone(&self) -> Self {40 LayeredHashMap(self.0.clone())41 }42}4344impl<K: Hash + Eq, V> Default for LayeredHashMap<K, V> {45 fn default() -> Self {46 LayeredHashMap(Rc::new(LayeredHashMapInternals {47 parent: None,48 current: HashMap::new(),49 }))50 }51}