use std::{any::TypeId, marker::PhantomData};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value;
#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
pub struct UnknownStateType;
#[derive(Clone, Debug)]
pub struct TemplateStateWithType<T: Serialize + DeserializeOwned> {
pub(crate) state: Value,
ty: PhantomData<T>,
}
impl<T: Serialize + DeserializeOwned + 'static> TemplateStateWithType<T> {
pub(crate) fn into_concrete(self) -> Result<T, serde_json::Error> {
serde_json::from_value(self.state)
}
pub fn empty() -> Self {
Self {
state: Value::Null,
ty: PhantomData,
}
}
pub fn is_empty(&self) -> bool {
self.state.is_null() || TypeId::of::<T>() == TypeId::of::<()>()
}
pub(crate) fn from_str(s: &str) -> Result<Self, serde_json::Error> {
let state = Self {
state: serde_json::from_str(s)?,
ty: PhantomData,
};
Ok(state)
}
pub fn from_value(v: Value) -> Self {
Self {
state: v,
ty: PhantomData,
}
}
pub(crate) fn change_type<U: Serialize + DeserializeOwned>(self) -> TemplateStateWithType<U> {
TemplateStateWithType {
state: self.state,
ty: PhantomData,
}
}
}
impl<T: Serialize + DeserializeOwned> From<T> for TemplateState {
fn from(state: T) -> Self {
Self {
state: serde_json::to_value(state).expect("serializing template state failed (this is almost certainly due to non-string map keys in your types, which can't be serialized by serde)"),
ty: PhantomData,
}
}
}
pub type TemplateState = TemplateStateWithType<UnknownStateType>;