1use std::fmt;
13
14use serde_json::{Map, Value};
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum SynthError {
19 Corrupt(String),
21 UnknownKey(String),
23}
24
25impl SynthError {
26 pub fn corrupt(expected: impl Into<String>) -> Self {
28 Self::Corrupt(expected.into())
29 }
30}
31
32impl fmt::Display for SynthError {
33 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34 match self {
35 Self::Corrupt(message) => formatter.write_str(message),
36 Self::UnknownKey(key) => write!(formatter, "Unable to find synthesizer with key: [{key}]"),
37 }
38 }
39}
40
41impl std::error::Error for SynthError {}
42
43pub type Result<T, E = SynthError> = std::result::Result<T, E>;
45
46pub trait Synth: Sized + Send + Sync + 'static {
51 const KEY: &'static str;
53
54 fn dehydrate(&self) -> Option<(Value, Map<String, Value>)>;
56
57 fn hydrate(value: &Value, meta: Option<&Map<String, Value>>) -> Result<Self>;
63}
64
65#[must_use]
70pub fn split_tuple(value: &Value) -> (Value, Option<Map<String, Value>>) {
71 let Value::Array(parts) = value else {
72 return (value.clone(), None);
73 };
74
75 if parts.len() != 2 {
76 return (value.clone(), None);
77 }
78
79 let meta = match &parts[1] {
80 Value::Object(meta) if meta.contains_key(SYNTH_KEY) => Some(meta.clone()),
81 _ => None,
82 };
83
84 match meta {
85 Some(meta) => (parts[0].clone(), Some(meta)),
86 None => (value.clone(), None),
87 }
88}
89
90pub const SYNTH_KEY: &str = "s";
92
93pub(crate) fn with_key(key: &'static str, mut meta: Map<String, Value>) -> Map<String, Value> {
95 meta.insert(SYNTH_KEY.to_owned(), Value::from(key));
96 meta
97}
98
99#[derive(Debug, Clone, Default, PartialEq)]
101pub struct Arr(pub Vec<Value>);
102
103impl Synth for Arr {
104 const KEY: &'static str = "arr";
105
106 fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
107 Some((Value::Array(self.0.clone()), with_key(Self::KEY, Map::new())))
108 }
109
110 fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
111 match value {
112 Value::Array(values) => Ok(Self(values.clone())),
113 _ => Err(SynthError::corrupt("an array")),
114 }
115 }
116}
117
118#[derive(Debug, Clone, Default, PartialEq)]
120pub struct Std(pub Map<String, Value>);
121
122impl Synth for Std {
123 const KEY: &'static str = "std";
124
125 fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
126 Some((Value::Object(self.0.clone()), with_key(Self::KEY, Map::new())))
127 }
128
129 fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
130 match value {
131 Value::Object(map) => Ok(Self(map.clone())),
132 _ => Err(SynthError::corrupt("an object")),
133 }
134 }
135}
136
137#[derive(Debug, Clone, Default, PartialEq, Eq)]
139pub struct Str(pub String);
140
141impl Synth for Str {
142 const KEY: &'static str = "str";
143
144 fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
145 None
146 }
147
148 fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
149 value
150 .as_str()
151 .map(|text| Self(text.to_owned()))
152 .ok_or_else(|| SynthError::corrupt("a string"))
153 }
154}
155
156#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
158pub struct Int(pub i64);
159
160impl Synth for Int {
161 const KEY: &'static str = "int";
162
163 fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
164 None
165 }
166
167 fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
168 value
169 .as_i64()
170 .map(Self)
171 .ok_or_else(|| SynthError::corrupt("an integer"))
172 }
173}
174
175#[derive(Debug, Clone, Copy, Default, PartialEq)]
177pub struct Float(pub f64);
178
179impl Synth for Float {
180 const KEY: &'static str = "float";
181
182 fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
183 None
184 }
185
186 fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
187 value.as_f64().map(Self).ok_or_else(|| SynthError::corrupt("a number"))
188 }
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194
195 #[test]
196 fn a_synthesized_value_carries_its_key_in_the_metadata() {
197 let (value, meta) = Arr(vec![Value::from(1)]).dehydrate().expect("a tuple");
198
199 assert_eq!(value, serde_json::json!([1]));
200 assert_eq!(meta[SYNTH_KEY], serde_json::json!("arr"));
201 }
202
203 #[test]
204 fn a_plain_value_has_no_tuple() {
205 assert_eq!(Str("hello".to_owned()).dehydrate(), None);
206 assert_eq!(Int(3).dehydrate(), None);
207 }
208
209 #[test]
210 fn only_a_tuple_with_a_key_is_split() {
211 let tuple = serde_json::json!(["value", {"s": "arr"}]);
212 let (value, meta) = split_tuple(&tuple);
213 assert_eq!(value, serde_json::json!("value"));
214 assert_eq!(meta.expect("metadata")[SYNTH_KEY], serde_json::json!("arr"));
215
216 let plain = serde_json::json!(["a", "b"]);
217 assert_eq!(split_tuple(&plain), (plain.clone(), None));
218
219 let no_key = serde_json::json!([1, {"x": 1}]);
220 assert_eq!(split_tuple(&no_key), (no_key.clone(), None));
221 }
222
223 #[test]
224 fn a_mismatched_value_is_corrupt_not_a_panic() {
225 assert_eq!(
226 Arr::hydrate(&serde_json::json!("nope"), None),
227 Err(SynthError::corrupt("an array"))
228 );
229 assert_eq!(
230 Int::hydrate(&serde_json::json!(1.5), None),
231 Err(SynthError::corrupt("an integer"))
232 );
233 assert!(Str::hydrate(&serde_json::json!(1), None).is_err());
234 }
235
236 #[test]
237 fn a_value_round_trips_through_its_synthesizer() {
238 let original = Std(Map::from_iter([("a".to_owned(), Value::from(1))]));
239 let (value, meta) = original.dehydrate().expect("a tuple");
240
241 assert_eq!(Std::hydrate(&value, Some(&meta)).expect("hydrates"), original);
242 }
243}