use std::collections::HashMap;
use std::hash::Hash;
use std::rc::Rc;
#[derive(Debug, Clone)]
pub struct Scope<K, V> {
bindings: Rc<HashMap<K, V>>,
}
impl<K, V> Default for Scope<K, V> {
fn default() -> Self {
Self {
bindings: Rc::new(HashMap::new()),
}
}
}
impl<K, V> Scope<K, V>
where
K: Clone + Eq + Hash,
V: Clone,
{
#[must_use]
#[inline]
pub fn new() -> Self {
Self::default()
}
#[must_use]
#[inline]
pub fn from_map(bindings: HashMap<K, V>) -> Self {
Self {
bindings: Rc::new(bindings),
}
}
#[must_use]
#[inline]
pub fn child(&self) -> Self {
Self {
bindings: Rc::clone(&self.bindings),
}
}
#[must_use]
#[inline]
pub fn get<Q>(&self, key: &Q) -> Option<&V>
where
K: std::borrow::Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.bindings.get(key)
}
#[must_use]
#[inline]
pub fn contains_key<Q>(&self, key: &Q) -> bool
where
K: std::borrow::Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.bindings.contains_key(key)
}
#[inline]
#[must_use]
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
Rc::make_mut(&mut self.bindings).insert(key, value)
}
#[must_use]
#[inline]
pub fn len(&self) -> usize {
self.bindings.len()
}
#[must_use]
#[inline]
pub fn is_empty(&self) -> bool {
self.bindings.is_empty()
}
}