vertigo 0.14.5

Reactive Real-DOM library with SSR for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;

use crate::driver_module::js_value::MapItem;
use crate::driver_module::js_value::js_json_struct::JsJsonNumber;
use crate::driver_module::js_value::js_object::JsObject;

use super::JsJsonContext;
use super::js_json_struct::JsJson;

pub trait JsJsonSerialize {
    fn to_json(self) -> JsJson;
}

/// Adds one field to a `JsJson::Object` under construction. Used by `AutoJsJson`.
///
/// The obvious way to write the derive is `BTreeMap::from([(k, v), ..])`, and the reason not
/// to is that the form is generic over the *length* of the array: the bulk-build path behind
/// it - `bulk_push`, `DedupSortedIter`, the sort - is instantiated once per distinct field
/// count, and every derived type in the program adds to the tally rather than sharing it.
/// Inserting one field at a time is a single instantiation the whole program shares.
///
/// `#[inline(never)]` because sharing is the point: a real application has hundreds of
/// derived fields, and LLVM would otherwise paste the tree descent into every one of them.
///
/// Keys arrive as `&'static str` because the derive only ever passes literals; allocating
/// here rather than at each caller is a little less code at every call site.
///
/// Collecting the fields into a `Vec` first and bulk-building from that was measured too - it
/// is one instantiation as well, but the heap allocation costs more than the bulk build saves,
/// and it was slower than this on every shape tried.
#[doc(hidden)]
#[inline(never)]
pub fn object_insert(object: &mut JsObject, key: &'static str, value: JsJson) {
    object.insert(key.to_string(), value);
}

pub trait JsJsonDeserialize
where
    Self: Sized,
{
    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext>;
}

impl JsJsonSerialize for String {
    fn to_json(self) -> JsJson {
        JsJson::String(self)
    }
}

impl JsJsonDeserialize for String {
    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
        match json {
            JsJson::String(value) => Ok(value),
            other => {
                let message = ["string expected, received ", other.typename()].concat();
                Err(context.add(message))
            }
        }
    }
}

/// The error of a JSON value that is not a number where the number type `name` was wanted -
/// out of line and generic over nothing, so that all the number types share it.
#[inline(never)]
fn number_expected(context: &JsJsonContext, name: &str, other: &JsJson) -> JsJsonContext {
    context.add(["number(", name, ") expected, received ", other.typename()].concat())
}

/// The error of a number that the integer type `name` cannot hold.
///
/// The number is printed through `i64` because `f64::to_string` here would link the float
/// formatter into every program that reads an integer: 25 KB of wasm for one error message.
#[inline(never)]
fn integer_expected(context: &JsJsonContext, name: &str, value: f64) -> JsJsonContext {
    let whole = value as i64;
    let received = if whole as f64 == value {
        whole.to_string()
    } else {
        "a fraction or a value beyond i64".to_string()
    };
    context.add(["integer(", name, ") expected, received ", &received].concat())
}

macro_rules! impl_serialize_number {
    ($($name:ty),+) => {
        $(
            impl JsJsonSerialize for $name {
                fn to_json(self) -> JsJson {
                    JsJson::Number(JsJsonNumber(self as f64))
                }
            }
        )+
    };
}

macro_rules! impl_deserialize_integer {
    ($($name:ty),+) => {
        $(
            /// A whole number within the range of the type; anything else is an error rather than
            /// a number clamped or cut to fit. JSON numbers are `f64`, so above 2^53 a value was
            /// already rounded on its way here.
            impl JsJsonDeserialize for $name {
                fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
                    match json {
                        JsJson::Number(JsJsonNumber(value)) => {
                            // `MAX` of the 64-bit types rounds up to 2^64 or 2^63. That is what
                            // `to_json` sends for it, and the cast below brings it back to `MAX`.
                            let in_range =
                                value >= <$name>::MIN as f64 && value <= <$name>::MAX as f64;
                            if value.fract() == 0.0 && in_range {
                                Ok(value as Self)
                            } else {
                                Err(integer_expected(&context, stringify!($name), value))
                            }
                        }
                        other => Err(number_expected(&context, stringify!($name), &other)),
                    }
                }
            }
        )+
    };
}

macro_rules! impl_deserialize_float {
    ($($name:ty),+) => {
        $(
            impl JsJsonDeserialize for $name {
                fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
                    match json {
                        JsJson::Number(JsJsonNumber(value)) => Ok(value as Self),
                        other => Err(number_expected(&context, stringify!($name), &other)),
                    }
                }
            }
        )+
    };
}

impl_serialize_number!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64);
impl_deserialize_integer!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
impl_deserialize_float!(f32, f64);

impl JsJsonSerialize for bool {
    fn to_json(self) -> JsJson {
        match self {
            false => JsJson::False,
            true => JsJson::True,
        }
    }
}

impl JsJsonDeserialize for bool {
    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
        match json {
            JsJson::False => Ok(false),
            JsJson::True => Ok(true),
            other => {
                let message = ["bool expected, received ", other.typename()].concat();
                Err(context.add(message))
            }
        }
    }
}

impl JsJsonSerialize for () {
    fn to_json(self) -> JsJson {
        JsJson::Object(JsObject::default())
    }
}

impl JsJsonDeserialize for () {
    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
        let map = json.get_hashmap(&context)?;

        if !map.is_empty() {
            let message = "Empty {} expected, inner content received".to_string();
            return Err(context.add(message));
        }

        Ok(())
    }
}

impl JsJsonSerialize for &str {
    fn to_json(self) -> JsJson {
        JsJson::String(self.into())
    }
}

impl<T: JsJsonSerialize> JsJsonSerialize for Vec<T> {
    fn to_json(self) -> JsJson {
        let mut list = Vec::new();

        for item in self {
            list.push(item.to_json());
        }

        JsJson::List(list)
    }
}

/// Bytes shared with what made them, f. ex. a drawing, travel as those of a `Vec<u8>` field do.
impl JsJsonSerialize for Arc<Vec<u8>> {
    fn to_json(self) -> JsJson {
        JsJson::Vec(Arc::unwrap_or_clone(self))
    }
}

impl JsJsonDeserialize for Arc<Vec<u8>> {
    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
        json.into_bytes(&context).map(Arc::new)
    }
}

impl<T: JsJsonDeserialize> JsJsonDeserialize for Vec<T> {
    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
        let items = list_items(&context, json)?;
        let mut list = Vec::new();

        for (index, item) in items.into_iter().enumerate() {
            list.push(T::from_json(context.add(index), item)?);
        }

        Ok(list)
    }
}

/// The items of a list, for [`Vec::from_json`] - out of line and generic over nothing, so
/// that each type read as a list adds only its own loop.
#[inline(never)]
fn list_items(context: &JsJsonContext, json: JsJson) -> Result<Vec<JsJson>, JsJsonContext> {
    match json {
        JsJson::List(items) => Ok(items),
        other => {
            let message = ["List expected, received ", other.typename()].concat();
            Err(context.add(message))
        }
    }
}

impl<T: JsJsonSerialize> JsJsonSerialize for Option<T> {
    fn to_json(self) -> JsJson {
        match self {
            Some(value) => value.to_json(),
            None => JsJson::Null,
        }
    }
}

impl<T: JsJsonDeserialize> JsJsonDeserialize for Option<T> {
    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
        if let JsJson::Null = json {
            return Ok(None);
        }

        Ok(Some(T::from_json(context, json)?))
    }
}

impl<T: JsJsonSerialize> JsJsonSerialize for HashMap<String, T> {
    fn to_json(self) -> JsJson {
        let mut result = JsObject::new();

        for (key, item) in self {
            result.insert(key, item.to_json());
        }

        JsJson::Object(result)
    }
}

impl<T: JsJsonDeserialize> JsJsonDeserialize for HashMap<String, T> {
    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
        let map = json.get_hashmap(&context)?;

        let mut result = HashMap::new();

        for (key, item) in map {
            let context = context.add(["field: '", key.as_str(), "'"].concat());
            let value = T::from_json(context, item)?;
            result.insert(key, value);
        }

        Ok(result)
    }
}

impl<K: JsJsonSerialize + JsJsonDeserialize, T: JsJsonSerialize + JsJsonDeserialize> JsJsonSerialize
    for BTreeMap<K, T>
{
    fn to_json(self) -> JsJson {
        let mut result = Vec::<JsJson>::new();

        for (key, item) in self {
            result.push(MapItem { key, value: item }.to_json());
        }

        JsJson::List(result)
    }
}

impl<K: JsJsonSerialize + JsJsonDeserialize + Ord, T: JsJsonSerialize + JsJsonDeserialize>
    JsJsonDeserialize for BTreeMap<K, T>
{
    fn from_json(context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
        let mut result = BTreeMap::new();

        match json {
            // Native vertigo form: a list of `{k, v}` items.
            JsJson::List(list) => {
                for (index, item) in list.into_iter().enumerate() {
                    let item = from_json::<MapItem<K, T>>(item)
                        .map_err(|err| context.add(format!("index={index} error={err}")))?;

                    if result.insert(item.key, item.value).is_some() {
                        return Err(context.add("Duplicate key"));
                    }
                }
            }
            // Interop form (e.g. produced by serde): a plain object `{"key": value}`.
            // Synthesize a `{k, v}` MapItem per entry and delegate. Non-String keys
            // surface a graceful error because the key arrives as a JsJson::String.
            JsJson::Object(obj) => {
                for (key, value) in obj {
                    let synthetic = JsJson::Object(JsObject::from([
                        ("k".to_string(), JsJson::String(key.clone())),
                        ("v".to_string(), value),
                    ]));

                    let item = from_json::<MapItem<K, T>>(synthetic)
                        .map_err(|err| context.add(format!("key='{key}' error={err}")))?;

                    if result.insert(item.key, item.value).is_some() {
                        return Err(context.add("Duplicate key"));
                    }
                }
            }
            other => {
                let message = ["list or object expected, received ", other.typename()].concat();
                return Err(context.add(message));
            }
        }

        Ok(result)
    }
}

/// Deserialize from JsJson to T
pub fn from_json<T: JsJsonDeserialize>(json: JsJson) -> Result<T, String> {
    let context = JsJsonContext::new("root");
    let result = T::from_json(context, json);
    result.map_err(|context| context.convert_to_string())
}

/// Serialize T to JsJson
pub fn to_json<T: JsJsonSerialize>(value: T) -> JsJson {
    value.to_json()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::JsObject;

    #[derive(Debug, PartialEq, Clone)]
    struct Post {
        name: String,
        age: u64,
    }

    impl JsJsonSerialize for Post {
        fn to_json(self) -> JsJson {
            JsJson::Object(JsObject::from([
                ("name".to_string(), self.name.to_json()),
                ("age".to_string(), self.age.to_json()),
            ]))
        }
    }

    impl JsJsonDeserialize for Post {
        fn from_json(context: JsJsonContext, mut json: JsJson) -> Result<Self, JsJsonContext> {
            Ok(Self {
                name: json.get_property(&context, "name")?,
                age: json.get_property(&context, "age")?,
            })
        }
    }

    #[test]
    fn aaaa() {
        let aaa = JsJson::String("aaa".into());
        let aaa_post = from_json::<Post>(aaa);
        assert_eq!(
            aaa_post,
            Err(String::from("root -> object expected, received string"))
        );

        let bbb = Post {
            name: "dsada".into(),
            age: 33,
        };

        let ccc = bbb.clone().to_json();
        let Ok(ddd) = from_json::<Post>(ccc) else {
            unreachable!();
        };
        assert_eq!(bbb, ddd);
    }

    #[test]
    fn test_vec() {
        let aaa = Post {
            name: "aaa".into(),
            age: 11,
        };

        let bbb = Post {
            name: "bbb".into(),
            age: 22,
        };

        let ccc = vec![aaa, bbb];

        let ddd = ccc.clone().to_json();

        let Ok(eee) = from_json::<Vec<Post>>(ddd) else {
            unreachable!();
        };

        assert_eq!(ccc, eee);
    }

    #[test]
    fn test_unit() {
        let unit = JsJson::Object(JsObject::default());

        let Ok(()) = from_json::<()>(unit.clone()) else {
            unreachable!();
        };

        let unit2 = to_json(());

        assert_eq!(unit2, unit)
    }

    #[test]
    fn test_serialize_to_string() {
        let data: Vec<u8> = b"Hello, world!".to_vec();

        let encoded = data
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>();

        let decoded = (0..encoded.len())
            .step_by(2)
            .filter_map(|i| {
                let decoded_i = u8::from_str_radix(&encoded[i..i + 2], 16);
                assert!(decoded_i.is_ok());
                decoded_i.ok()
            })
            .collect::<Vec<u8>>();

        println!("Original: {}", String::from_utf8_lossy(&decoded));
    }
}