use std::fmt;
use serde_json::{Map, Value};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SynthError {
Corrupt(String),
UnknownKey(String),
}
impl SynthError {
pub fn corrupt(expected: impl Into<String>) -> Self {
Self::Corrupt(expected.into())
}
}
impl fmt::Display for SynthError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Corrupt(message) => formatter.write_str(message),
Self::UnknownKey(key) => write!(formatter, "Unable to find synthesizer with key: [{key}]"),
}
}
}
impl std::error::Error for SynthError {}
pub type Result<T, E = SynthError> = std::result::Result<T, E>;
pub trait Synth: Sized + Send + Sync + 'static {
const KEY: &'static str;
fn dehydrate(&self) -> Option<(Value, Map<String, Value>)>;
fn hydrate(value: &Value, meta: Option<&Map<String, Value>>) -> Result<Self>;
}
#[must_use]
pub fn split_tuple(value: &Value) -> (Value, Option<Map<String, Value>>) {
let Value::Array(parts) = value else {
return (value.clone(), None);
};
if parts.len() != 2 {
return (value.clone(), None);
}
let meta = match &parts[1] {
Value::Object(meta) if meta.contains_key(SYNTH_KEY) => Some(meta.clone()),
_ => None,
};
match meta {
Some(meta) => (parts[0].clone(), Some(meta)),
None => (value.clone(), None),
}
}
pub const SYNTH_KEY: &str = "s";
pub(crate) fn with_key(key: &'static str, mut meta: Map<String, Value>) -> Map<String, Value> {
meta.insert(SYNTH_KEY.to_owned(), Value::from(key));
meta
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Arr(pub Vec<Value>);
impl Synth for Arr {
const KEY: &'static str = "arr";
fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
Some((Value::Array(self.0.clone()), with_key(Self::KEY, Map::new())))
}
fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
match value {
Value::Array(values) => Ok(Self(values.clone())),
_ => Err(SynthError::corrupt("an array")),
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Std(pub Map<String, Value>);
impl Synth for Std {
const KEY: &'static str = "std";
fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
Some((Value::Object(self.0.clone()), with_key(Self::KEY, Map::new())))
}
fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
match value {
Value::Object(map) => Ok(Self(map.clone())),
_ => Err(SynthError::corrupt("an object")),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Str(pub String);
impl Synth for Str {
const KEY: &'static str = "str";
fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
None
}
fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
value
.as_str()
.map(|text| Self(text.to_owned()))
.ok_or_else(|| SynthError::corrupt("a string"))
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Int(pub i64);
impl Synth for Int {
const KEY: &'static str = "int";
fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
None
}
fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
value
.as_i64()
.map(Self)
.ok_or_else(|| SynthError::corrupt("an integer"))
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Float(pub f64);
impl Synth for Float {
const KEY: &'static str = "float";
fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
None
}
fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
value.as_f64().map(Self).ok_or_else(|| SynthError::corrupt("a number"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_synthesized_value_carries_its_key_in_the_metadata() {
let (value, meta) = Arr(vec![Value::from(1)]).dehydrate().expect("a tuple");
assert_eq!(value, serde_json::json!([1]));
assert_eq!(meta[SYNTH_KEY], serde_json::json!("arr"));
}
#[test]
fn a_plain_value_has_no_tuple() {
assert_eq!(Str("hello".to_owned()).dehydrate(), None);
assert_eq!(Int(3).dehydrate(), None);
}
#[test]
fn only_a_tuple_with_a_key_is_split() {
let tuple = serde_json::json!(["value", {"s": "arr"}]);
let (value, meta) = split_tuple(&tuple);
assert_eq!(value, serde_json::json!("value"));
assert_eq!(meta.expect("metadata")[SYNTH_KEY], serde_json::json!("arr"));
let plain = serde_json::json!(["a", "b"]);
assert_eq!(split_tuple(&plain), (plain.clone(), None));
let no_key = serde_json::json!([1, {"x": 1}]);
assert_eq!(split_tuple(&no_key), (no_key.clone(), None));
}
#[test]
fn a_mismatched_value_is_corrupt_not_a_panic() {
assert_eq!(
Arr::hydrate(&serde_json::json!("nope"), None),
Err(SynthError::corrupt("an array"))
);
assert_eq!(
Int::hydrate(&serde_json::json!(1.5), None),
Err(SynthError::corrupt("an integer"))
);
assert!(Str::hydrate(&serde_json::json!(1), None).is_err());
}
#[test]
fn a_value_round_trips_through_its_synthesizer() {
let original = Std(Map::from_iter([("a".to_owned(), Value::from(1))]));
let (value, meta) = original.dehydrate().expect("a tuple");
assert_eq!(Std::hydrate(&value, Some(&meta)).expect("hydrates"), original);
}
}