use std::borrow::Cow;
use std::marker::PhantomData;
use crate::context::Context;
pub struct ContextKey<T> {
pub name: Cow<'static, str>,
_marker: PhantomData<T>,
}
impl<T> ContextKey<T> {
#[must_use]
pub const fn new(name: &'static str) -> Self {
Self {
name: Cow::Borrowed(name),
_marker: PhantomData,
}
}
#[must_use]
pub fn scoped(&self, suffix: &str) -> ContextKey<T> {
ContextKey {
name: Cow::Owned(format!("{}.{}", self.name, suffix)),
_marker: PhantomData,
}
}
}
impl<T: serde::de::DeserializeOwned> ContextKey<T> {
pub fn get<S>(&self, ctx: &Context<S>) -> Option<T> {
let map = ctx.data.read();
let val = map.get(self.name.as_ref())?;
serde_json::from_value(val.clone()).ok()
}
pub fn exists<S>(&self, ctx: &Context<S>) -> bool {
ctx.data.read().contains_key(self.name.as_ref())
}
}
impl<T: serde::Serialize> ContextKey<T> {
pub fn set<S>(&self, ctx: &Context<S>, value: T) {
let mut map = ctx.data.write();
if let Ok(v) = serde_json::to_value(value) {
map.insert(self.name.to_string(), v);
}
}
pub fn delete<S>(&self, ctx: &Context<S>) {
let mut map = ctx.data.write();
map.remove(self.name.as_ref());
}
}