Skip to main content

brrrty_node/
decode.rs

1//! The worker's wire forms (see `worker/encode.mjs`), decoded into Brrrty
2//! values. Anything not exactly one of the forms is an error: the worker
3//! and this file are one protocol, so a mismatch is a bug, never data.
4
5use std::sync::Arc;
6
7use brrrty_js::Value;
8use brrrty_js::runtime::{Decoded, FnHandle, PathPart};
9use serde_json::Value as Json;
10
11/// Decode one encoded value.
12pub fn decode(json: &Json) -> Result<Decoded, String> {
13    let mut d = Decoded {
14        value: Value::Undefined,
15        functions: Vec::new(),
16        refused: Vec::new(),
17    };
18    let mut path = Vec::new();
19    d.value = value(json, &mut path, &mut d, false)?;
20    Ok(d)
21}
22
23fn value(
24    json: &Json,
25    path: &mut Vec<PathPart>,
26    d: &mut Decoded,
27    in_array: bool,
28) -> Result<Value, String> {
29    Ok(match json {
30        Json::Null => Value::Null,
31        Json::Bool(b) => Value::Bool(*b),
32        Json::Number(n) => Value::Number(
33            n.as_f64()
34                .ok_or_else(|| format!("number out of range: {n}"))?,
35        ),
36        Json::String(s) => Value::String(s.as_str().into()),
37        Json::Array(items) => {
38            let mut out = Vec::with_capacity(items.len());
39            for (i, item) in items.iter().enumerate() {
40                path.push(PathPart::Index(i));
41                out.push(value(item, path, d, true)?);
42                path.pop();
43            }
44            Value::Array(Arc::new(out))
45        }
46        Json::Object(o) => {
47            let mut it = o.iter();
48            let (Some((tag, body)), None) = (it.next(), it.next()) else {
49                return Err(format!("not a wire form: {json}"));
50            };
51            match (tag.as_str(), body) {
52                ("$o", Json::Array(entries)) => {
53                    let mut out = indexmap::IndexMap::with_capacity(entries.len());
54                    for entry in entries {
55                        let Some([Json::String(k), v]) = entry.as_array().map(Vec::as_slice) else {
56                            return Err(format!("not an object entry: {entry}"));
57                        };
58                        path.push(PathPart::Key(k.clone()));
59                        let v = value(v, path, d, false)?;
60                        path.pop();
61                        out.insert(k.clone(), v);
62                    }
63                    Value::Object(Arc::new(out))
64                }
65                ("$u", _) => Value::Undefined,
66                ("$hole", _) if in_array => Value::Undefined,
67                ("$n", Json::String(s)) => Value::Number(match s.as_str() {
68                    "-0" => -0.0,
69                    "NaN" => f64::NAN,
70                    "Infinity" => f64::INFINITY,
71                    "-Infinity" => f64::NEG_INFINITY,
72                    other => return Err(format!("not a special number: {other}")),
73                }),
74                ("$d", Json::Number(ms)) => {
75                    let ms = ms
76                        .as_f64()
77                        .filter(|m| m.fract() == 0.0)
78                        .ok_or_else(|| format!("not a time: {ms}"))?;
79                    match chrono::DateTime::from_timestamp_millis(ms as i64) {
80                        Some(t) => Value::Date(t.fixed_offset()),
81                        None => {
82                            d.refused.push((
83                                path.clone(),
84                                "a Date too far from 1970 for Brrrty to print".to_string(),
85                            ));
86                            Value::Undefined
87                        }
88                    }
89                }
90                ("$f", Json::Number(h)) => {
91                    let h = h
92                        .as_u64()
93                        .and_then(|h| u32::try_from(h).ok())
94                        .ok_or_else(|| format!("not a function handle: {h}"))?;
95                    d.functions.push((path.clone(), FnHandle(h)));
96                    Value::Undefined
97                }
98                ("$x", Json::String(what)) => {
99                    d.refused.push((path.clone(), what.clone()));
100                    Value::Undefined
101                }
102                _ => return Err(format!("not a wire form: {json}")),
103            }
104        }
105    })
106}