use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Context<T = Value> {
data: HashMap<String, Value>,
_phantom: std::marker::PhantomData<T>,
}
impl<T> Context<T> {
pub fn new(data: HashMap<String, Value>) -> Self {
Self {
data,
_phantom: std::marker::PhantomData,
}
}
pub fn empty() -> Self {
Self {
data: HashMap::new(),
_phantom: std::marker::PhantomData,
}
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.data.get(key)
}
pub fn insert(self, key: String, value: Value) -> Context<T> {
let mut new_data = self.data;
new_data.insert(key, value);
Context {
data: new_data,
_phantom: std::marker::PhantomData,
}
}
pub fn insert_as<U>(self, key: String, value: Value) -> Context<U> {
let mut new_data = self.data;
new_data.insert(key, value);
Context {
data: new_data,
_phantom: std::marker::PhantomData,
}
}
pub fn with_mutation(&self) -> MutableContext {
MutableContext {
data: self.data.clone(),
}
}
pub fn merge(mut self, other: &Context<T>) -> Context<T> {
for (key, value) in &other.data {
self.data.insert(key.clone(), value.clone());
}
self
}
pub fn to_hashmap(&self) -> HashMap<String, Value> {
self.data.clone()
}
pub fn data(&self) -> &HashMap<String, Value> {
&self.data
}
}
impl Context<Value> {
pub fn from_hashmap(data: HashMap<String, Value>) -> Self {
Self::new(data)
}
}
impl<T> Default for Context<T> {
fn default() -> Self {
Self::empty()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MutableContext {
data: HashMap<String, Value>,
}
impl MutableContext {
pub fn new() -> Self {
Self {
data: HashMap::new(),
}
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.data.get(key)
}
pub fn set(&mut self, key: String, value: Value) {
self.data.insert(key, value);
}
pub fn to_immutable<T>(self) -> Context<T> {
Context {
data: self.data,
_phantom: std::marker::PhantomData,
}
}
pub fn data(&self) -> &HashMap<String, Value> {
&self.data
}
}
impl Default for MutableContext {
fn default() -> Self {
Self::new()
}
}