use crate::value::{ToValue, Value, Values};
use alloc::borrow::Cow;
use core::{borrow::Borrow, hash::Hash};
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HashValues<'v, 's: 'v, K: Borrow<str> + Hash + Eq>(HashMap<K, Value<'v, 's>>);
impl<'v, 's, K: Borrow<str> + Hash + Eq> HashValues<'v, 's, K> {
#[inline]
pub fn new() -> Self {
Self(HashMap::new())
}
#[inline]
pub fn insert(&mut self, key: K, val: impl Into<Value<'v, 's>>) -> Option<Value<'v, 's>> {
self.0.insert(key, val.into())
}
#[inline]
pub fn remove(&mut self, key: &str) -> Option<Value<'v, 's>> {
self.0.remove(key)
}
#[inline]
pub fn get(&self, key: &str) -> Option<&Value<'v, 's>> {
self.0.get(key)
}
}
impl<'v, 's, K> Values<'v, 's> for &HashValues<'v, 's, K>
where
K: Borrow<str> + Hash + Eq,
{
#[inline]
fn var(&self, name: &str) -> Option<Cow<'_, Value<'v, 's>>> {
self.get(name).map(Cow::Borrowed)
}
}
impl<'v, 's, K> Values<'v, 's> for &HashMap<K, Option<Value<'v, 's>>>
where
K: Borrow<str> + Hash + Eq,
{
#[inline]
fn var(&self, name: &str) -> Option<Cow<'_, Value<'v, 's>>> {
self.get(name).and_then(Option::as_ref).map(Cow::Borrowed)
}
}
impl<'v, 's, K> Values<'v, 's> for &HashMap<K, Value<'v, 's>>
where
K: Borrow<str> + Hash + Eq,
{
#[inline]
fn var(&self, name: &str) -> Option<Cow<'_, Value<'v, 's>>> {
self.get(name).map(Cow::Borrowed)
}
}
impl<'v, 's: 'v, K> Values<'v, 's> for &HashMap<K, Box<dyn ToValue<'v, 's>>>
where
K: Borrow<str> + Hash + Eq,
{
#[inline]
fn var(&self, name: &str) -> Option<Cow<'_, Value<'v, 's>>> {
self.get(name).map(|val| val.to_value()).map(Cow::Owned)
}
}
impl<'v, 's: 'v, K> Values<'v, 's> for &HashMap<K, &'v dyn ToValue<'v, 's>>
where
K: Borrow<str> + Hash + Eq,
{
#[inline]
fn var(&self, name: &str) -> Option<Cow<'_, Value<'v, 's>>> {
self.get(name).map(|val| val.to_value()).map(Cow::Owned)
}
}