Skip to main content

vertigo/driver_module/js_value/
serialize.rs

1use std::collections::{BTreeMap, HashMap};
2use std::sync::Arc;
3
4use crate::driver_module::js_value::MapItem;
5use crate::driver_module::js_value::js_json_struct::JsJsonNumber;
6use crate::driver_module::js_value::js_object::JsObject;
7
8use super::JsJsonContext;
9use super::js_json_struct::JsJson;
10
11pub trait JsJsonSerialize {
12    fn to_json(self) -> JsJson;
13}
14
15/// Adds one field to a `JsJson::Object` under construction. Used by `AutoJsJson`.
16///
17/// The obvious way to write the derive is `BTreeMap::from([(k, v), ..])`, and the reason not
18/// to is that the form is generic over the *length* of the array: the bulk-build path behind
19/// it - `bulk_push`, `DedupSortedIter`, the sort - is instantiated once per distinct field
20/// count, and every derived type in the program adds to the tally rather than sharing it.
21/// Inserting one field at a time is a single instantiation the whole program shares.
22///
23/// `#[inline(never)]` because sharing is the point: a real application has hundreds of
24/// derived fields, and LLVM would otherwise paste the tree descent into every one of them.
25///
26/// Keys arrive as `&'static str` because the derive only ever passes literals; allocating
27/// here rather than at each caller is a little less code at every call site.
28///
29/// Collecting the fields into a `Vec` first and bulk-building from that was measured too - it
30/// is one instantiation as well, but the heap allocation costs more than the bulk build saves,
31/// and it was slower than this on every shape tried.
32#[doc(hidden)]
33#[inline(never)]
34pub fn object_insert(object: &mut JsObject, key: &'static str, value: JsJson) {
35    object.insert(key.to_string(), value);
36}
37
38pub trait JsJsonDeserialize
39where
40    Self: Sized,
41{
42    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext>;
43}
44
45impl JsJsonSerialize for String {
46    fn to_json(self) -> JsJson {
47        JsJson::String(self)
48    }
49}
50
51impl JsJsonDeserialize for String {
52    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
53        match json {
54            JsJson::String(value) => Ok(value),
55            other => {
56                let message = ["string expected, received ", other.typename()].concat();
57                Err(context.add(message))
58            }
59        }
60    }
61}
62
63/// The error of a JSON value that is not a number where the number type `name` was wanted -
64/// out of line and generic over nothing, so that all the number types share it.
65#[inline(never)]
66fn number_expected(context: &JsJsonContext, name: &str, other: &JsJson) -> JsJsonContext {
67    context.add(["number(", name, ") expected, received ", other.typename()].concat())
68}
69
70/// The error of a number that the integer type `name` cannot hold.
71///
72/// The number is printed through `i64` because `f64::to_string` here would link the float
73/// formatter into every program that reads an integer: 25 KB of wasm for one error message.
74#[inline(never)]
75fn integer_expected(context: &JsJsonContext, name: &str, value: f64) -> JsJsonContext {
76    let whole = value as i64;
77    let received = if whole as f64 == value {
78        whole.to_string()
79    } else {
80        "a fraction or a value beyond i64".to_string()
81    };
82    context.add(["integer(", name, ") expected, received ", &received].concat())
83}
84
85macro_rules! impl_serialize_number {
86    ($($name:ty),+) => {
87        $(
88            impl JsJsonSerialize for $name {
89                fn to_json(self) -> JsJson {
90                    JsJson::Number(JsJsonNumber(self as f64))
91                }
92            }
93        )+
94    };
95}
96
97macro_rules! impl_deserialize_integer {
98    ($($name:ty),+) => {
99        $(
100            /// A whole number within the range of the type; anything else is an error rather than
101            /// a number clamped or cut to fit. JSON numbers are `f64`, so above 2^53 a value was
102            /// already rounded on its way here.
103            impl JsJsonDeserialize for $name {
104                fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
105                    match json {
106                        JsJson::Number(JsJsonNumber(value)) => {
107                            // `MAX` of the 64-bit types rounds up to 2^64 or 2^63. That is what
108                            // `to_json` sends for it, and the cast below brings it back to `MAX`.
109                            let in_range =
110                                value >= <$name>::MIN as f64 && value <= <$name>::MAX as f64;
111                            if value.fract() == 0.0 && in_range {
112                                Ok(value as Self)
113                            } else {
114                                Err(integer_expected(&context, stringify!($name), value))
115                            }
116                        }
117                        other => Err(number_expected(&context, stringify!($name), &other)),
118                    }
119                }
120            }
121        )+
122    };
123}
124
125macro_rules! impl_deserialize_float {
126    ($($name:ty),+) => {
127        $(
128            impl JsJsonDeserialize for $name {
129                fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
130                    match json {
131                        JsJson::Number(JsJsonNumber(value)) => Ok(value as Self),
132                        other => Err(number_expected(&context, stringify!($name), &other)),
133                    }
134                }
135            }
136        )+
137    };
138}
139
140impl_serialize_number!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64);
141impl_deserialize_integer!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
142impl_deserialize_float!(f32, f64);
143
144impl JsJsonSerialize for bool {
145    fn to_json(self) -> JsJson {
146        match self {
147            false => JsJson::False,
148            true => JsJson::True,
149        }
150    }
151}
152
153impl JsJsonDeserialize for bool {
154    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
155        match json {
156            JsJson::False => Ok(false),
157            JsJson::True => Ok(true),
158            other => {
159                let message = ["bool expected, received ", other.typename()].concat();
160                Err(context.add(message))
161            }
162        }
163    }
164}
165
166impl JsJsonSerialize for () {
167    fn to_json(self) -> JsJson {
168        JsJson::Object(JsObject::default())
169    }
170}
171
172impl JsJsonDeserialize for () {
173    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
174        let map = json.get_hashmap(&context)?;
175
176        if !map.is_empty() {
177            let message = "Empty {} expected, inner content received".to_string();
178            return Err(context.add(message));
179        }
180
181        Ok(())
182    }
183}
184
185impl JsJsonSerialize for &str {
186    fn to_json(self) -> JsJson {
187        JsJson::String(self.into())
188    }
189}
190
191impl<T: JsJsonSerialize> JsJsonSerialize for Vec<T> {
192    fn to_json(self) -> JsJson {
193        let mut list = Vec::new();
194
195        for item in self {
196            list.push(item.to_json());
197        }
198
199        JsJson::List(list)
200    }
201}
202
203/// Bytes shared with what made them, f. ex. a drawing, travel as those of a `Vec<u8>` field do.
204impl JsJsonSerialize for Arc<Vec<u8>> {
205    fn to_json(self) -> JsJson {
206        JsJson::Vec(Arc::unwrap_or_clone(self))
207    }
208}
209
210impl JsJsonDeserialize for Arc<Vec<u8>> {
211    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
212        json.into_bytes(&context).map(Arc::new)
213    }
214}
215
216impl<T: JsJsonDeserialize> JsJsonDeserialize for Vec<T> {
217    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
218        let items = list_items(&context, json)?;
219        let mut list = Vec::new();
220
221        for (index, item) in items.into_iter().enumerate() {
222            list.push(T::from_json(context.add(index), item)?);
223        }
224
225        Ok(list)
226    }
227}
228
229/// The items of a list, for [`Vec::from_json`] - out of line and generic over nothing, so
230/// that each type read as a list adds only its own loop.
231#[inline(never)]
232fn list_items(context: &JsJsonContext, json: JsJson) -> Result<Vec<JsJson>, JsJsonContext> {
233    match json {
234        JsJson::List(items) => Ok(items),
235        other => {
236            let message = ["List expected, received ", other.typename()].concat();
237            Err(context.add(message))
238        }
239    }
240}
241
242impl<T: JsJsonSerialize> JsJsonSerialize for Option<T> {
243    fn to_json(self) -> JsJson {
244        match self {
245            Some(value) => value.to_json(),
246            None => JsJson::Null,
247        }
248    }
249}
250
251impl<T: JsJsonDeserialize> JsJsonDeserialize for Option<T> {
252    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
253        if let JsJson::Null = json {
254            return Ok(None);
255        }
256
257        Ok(Some(T::from_json(context, json)?))
258    }
259}
260
261impl<T: JsJsonSerialize> JsJsonSerialize for HashMap<String, T> {
262    fn to_json(self) -> JsJson {
263        let mut result = JsObject::new();
264
265        for (key, item) in self {
266            result.insert(key, item.to_json());
267        }
268
269        JsJson::Object(result)
270    }
271}
272
273impl<T: JsJsonDeserialize> JsJsonDeserialize for HashMap<String, T> {
274    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
275        let map = json.get_hashmap(&context)?;
276
277        let mut result = HashMap::new();
278
279        for (key, item) in map {
280            let context = context.add(["field: '", key.as_str(), "'"].concat());
281            let value = T::from_json(context, item)?;
282            result.insert(key, value);
283        }
284
285        Ok(result)
286    }
287}
288
289impl<K: JsJsonSerialize + JsJsonDeserialize, T: JsJsonSerialize + JsJsonDeserialize> JsJsonSerialize
290    for BTreeMap<K, T>
291{
292    fn to_json(self) -> JsJson {
293        let mut result = Vec::<JsJson>::new();
294
295        for (key, item) in self {
296            result.push(MapItem { key, value: item }.to_json());
297        }
298
299        JsJson::List(result)
300    }
301}
302
303impl<K: JsJsonSerialize + JsJsonDeserialize + Ord, T: JsJsonSerialize + JsJsonDeserialize>
304    JsJsonDeserialize for BTreeMap<K, T>
305{
306    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
307        let mut result = BTreeMap::new();
308
309        match json {
310            // Native vertigo form: a list of `{k, v}` items.
311            JsJson::List(list) => {
312                for (index, item) in list.into_iter().enumerate() {
313                    let item = from_json::<MapItem<K, T>>(item)
314                        .map_err(|err| context.add(format!("index={index} error={err}")))?;
315
316                    if result.insert(item.key, item.value).is_some() {
317                        return Err(context.add("Duplicate key"));
318                    }
319                }
320            }
321            // Interop form (e.g. produced by serde): a plain object `{"key": value}`.
322            // Synthesize a `{k, v}` MapItem per entry and delegate. Non-String keys
323            // surface a graceful error because the key arrives as a JsJson::String.
324            JsJson::Object(obj) => {
325                for (key, value) in obj {
326                    let synthetic = JsJson::Object(JsObject::from([
327                        ("k".to_string(), JsJson::String(key.clone())),
328                        ("v".to_string(), value),
329                    ]));
330
331                    let item = from_json::<MapItem<K, T>>(synthetic)
332                        .map_err(|err| context.add(format!("key='{key}' error={err}")))?;
333
334                    if result.insert(item.key, item.value).is_some() {
335                        return Err(context.add("Duplicate key"));
336                    }
337                }
338            }
339            other => {
340                let message = ["list or object expected, received ", other.typename()].concat();
341                return Err(context.add(message));
342            }
343        }
344
345        Ok(result)
346    }
347}
348
349/// Deserialize from JsJson to T
350pub fn from_json<T: JsJsonDeserialize>(json: JsJson) -> Result<T, String> {
351    let context = JsJsonContext::new("root");
352    let result = T::from_json(context, json);
353    result.map_err(|context| context.convert_to_string())
354}
355
356/// Serialize T to JsJson
357pub fn to_json<T: JsJsonSerialize>(value: T) -> JsJson {
358    value.to_json()
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364    use crate::JsObject;
365
366    #[derive(Debug, PartialEq, Clone)]
367    struct Post {
368        name: String,
369        age: u64,
370    }
371
372    impl JsJsonSerialize for Post {
373        fn to_json(self) -> JsJson {
374            JsJson::Object(JsObject::from([
375                ("name".to_string(), self.name.to_json()),
376                ("age".to_string(), self.age.to_json()),
377            ]))
378        }
379    }
380
381    impl JsJsonDeserialize for Post {
382        fn from_json(context: JsJsonContext, mut json: JsJson) -> Result<Self, JsJsonContext> {
383            Ok(Self {
384                name: json.get_property(&context, "name")?,
385                age: json.get_property(&context, "age")?,
386            })
387        }
388    }
389
390    #[test]
391    fn aaaa() {
392        let aaa = JsJson::String("aaa".into());
393        let aaa_post = from_json::<Post>(aaa);
394        assert_eq!(
395            aaa_post,
396            Err(String::from("root -> object expected, received string"))
397        );
398
399        let bbb = Post {
400            name: "dsada".into(),
401            age: 33,
402        };
403
404        let ccc = bbb.clone().to_json();
405        let Ok(ddd) = from_json::<Post>(ccc) else {
406            unreachable!();
407        };
408        assert_eq!(bbb, ddd);
409    }
410
411    #[test]
412    fn test_vec() {
413        let aaa = Post {
414            name: "aaa".into(),
415            age: 11,
416        };
417
418        let bbb = Post {
419            name: "bbb".into(),
420            age: 22,
421        };
422
423        let ccc = vec![aaa, bbb];
424
425        let ddd = ccc.clone().to_json();
426
427        let Ok(eee) = from_json::<Vec<Post>>(ddd) else {
428            unreachable!();
429        };
430
431        assert_eq!(ccc, eee);
432    }
433
434    #[test]
435    fn test_unit() {
436        let unit = JsJson::Object(JsObject::default());
437
438        let Ok(()) = from_json::<()>(unit.clone()) else {
439            unreachable!();
440        };
441
442        let unit2 = to_json(());
443
444        assert_eq!(unit2, unit)
445    }
446
447    #[test]
448    fn test_serialize_to_string() {
449        let data: Vec<u8> = b"Hello, world!".to_vec();
450
451        let encoded = data
452            .iter()
453            .map(|b| format!("{:02x}", b))
454            .collect::<String>();
455
456        let decoded = (0..encoded.len())
457            .step_by(2)
458            .filter_map(|i| {
459                let decoded_i = u8::from_str_radix(&encoded[i..i + 2], 16);
460                assert!(decoded_i.is_ok());
461                decoded_i.ok()
462            })
463            .collect::<Vec<u8>>();
464
465        println!("Original: {}", String::from_utf8_lossy(&decoded));
466    }
467}