use scrusted_feel::{HostError, HostValue, Value};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
#[derive(Clone, Debug)]
pub enum MarkerOutput {
Value(Value),
Host(Arc<dyn HostValue>),
}
impl MarkerOutput {
pub fn into_value(self) -> Value {
match self {
MarkerOutput::Value(v) => v,
MarkerOutput::Host(h) => Value::Host(h),
}
}
}
impl From<Value> for MarkerOutput {
fn from(v: Value) -> Self {
MarkerOutput::Value(v)
}
}
pub type MarkerFn = Arc<dyn Fn(&Value) -> Result<MarkerOutput, HostError> + Send + Sync>;
#[derive(Clone, Default)]
pub struct Markers {
pub functions: HashMap<String, Option<MarkerFn>>,
pub computed: HashSet<String>,
}
impl Markers {
pub fn names(&self) -> Vec<String> {
let mut names: Vec<String> = self.functions.keys().cloned().collect();
names.sort();
names
}
}
#[derive(Debug, Clone)]
pub struct Placeholder {
pub marker: String,
pub source: Value,
}
impl HostValue for Placeholder {
fn read(&self) -> Result<Value, HostError> {
Ok(match &self.source {
Value::String(s) => Value::String(s.clone()),
other => Value::from(scrusted_feel::json::to_json(other).to_string()),
})
}
fn serialize(&self) -> Option<serde_json::Value> {
Some(serde_json::json!({ "marker": self.marker, "source": scrusted_feel::json::to_json(&self.source) }))
}
}
pub fn placeholder(name: &str) -> MarkerFn {
let name = name.to_string();
Arc::new(move |source: &Value| Ok(MarkerOutput::Host(Arc::new(Placeholder { marker: name.clone(), source: source.clone() }))))
}