use std::borrow::Cow;
use std::collections::HashMap;
use super::Value;
pub trait VariableStorage {
fn get(&self, name: &str) -> Option<Value>;
fn set(&mut self, name: &str, value: Value);
fn get_ref(&self, name: &str) -> Option<Cow<'_, Value>> {
self.get(name).map(Cow::Owned)
}
fn all_variables(&self) -> Vec<(String, Value)> {
Vec::new()
}
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct HashMapStorage {
map: HashMap<String, Value>,
}
impl HashMapStorage {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl VariableStorage for HashMapStorage {
fn get(&self, name: &str) -> Option<Value> {
self.map.get(name).cloned()
}
fn set(&mut self, name: &str, value: Value) {
self.map.insert(name.to_owned(), value);
}
fn get_ref(&self, name: &str) -> Option<Cow<'_, Value>> {
self.map.get(name).map(Cow::Borrowed)
}
fn all_variables(&self) -> Vec<(String, Value)> {
self.map
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
}
}
#[cfg(test)]
#[path = "storage_tests.rs"]
mod tests;