Skip to main content

rust_anything/
wire.rs

1//! The binary wire for Go and Java: values cross as compact bytes whose encoders and decoders
2//! are generated per type on both sides, without JSON text or reflection.
3//!
4//! Layout, little endian: `I64` and `F64` as 8 bytes, `Bool` as 1 byte. `Str`, `List`, `Map`
5//! and `Struct` start with a presence byte (0 for null/nil, 1 otherwise); strings then carry a
6//! u32 length and UTF-8 bytes, lists and maps a u32 count and their items (maps as string key,
7//! value). `Opt` is a presence byte and the value. `Tuple` (several results) is its items in order.
8
9use std::fmt::Write as _;
10
11/// A source-language type the wire carries. `native` is the type as the source spells it.
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub enum Ty {
14    I64(String),
15    F64(String),
16    Bool,
17    Str,
18    /// `array` marks a Java array (`int[]`) rather than a list.
19    List {
20        item: Box<Ty>,
21        native: String,
22        array: bool,
23    },
24    Map {
25        value: Box<Ty>,
26        native: String,
27    },
28    /// Fields: (source field name, JSON key, type).
29    Struct {
30        name: String,
31        fields: Vec<(String, String, Ty)>,
32    },
33    Opt {
34        inner: Box<Ty>,
35        native: String,
36    },
37    Tuple(Vec<Ty>),
38    // JS (TS) values: a JS number; a string as UTF-16 code units (lone surrogates survive);
39    // `undefined`/`null`/value; an object whose fields travel by index in the writer's key
40    // order (unknown keys by name); a string-keyed record; and any value, tagged by kind.
41    Num,
42    Str16,
43    OptJs {
44        inner: Box<Ty>,
45        nullable: bool,
46        undefinable: bool,
47    },
48    Obj(Vec<(String, Ty)>),
49    Map16(Box<Ty>),
50    Dyn,
51}
52
53/// The `wire::Schema` constant expression for a type, for `read_value`/`write_value`.
54pub fn schema_expr(t: &Ty) -> String {
55    match t {
56        Ty::I64(_) => "wire::Schema::I64".into(),
57        Ty::F64(_) => "wire::Schema::F64".into(),
58        Ty::Bool => "wire::Schema::Bool".into(),
59        Ty::Str => "wire::Schema::Str".into(),
60        Ty::List { item, .. } => format!("wire::Schema::List(&{})", schema_expr(item)),
61        Ty::Map { value, .. } => format!("wire::Schema::Map(&{})", schema_expr(value)),
62        Ty::Opt { inner, .. } => format!("wire::Schema::Opt(&{})", schema_expr(inner)),
63        Ty::Struct { fields, .. } => format!(
64            "wire::Schema::Struct(&[{}])",
65            fields
66                .iter()
67                .map(|(_, key, t)| format!("({key:?}, {})", schema_expr(t)))
68                .collect::<Vec<_>>()
69                .join(", ")
70        ),
71        Ty::Tuple(items) => format!(
72            "wire::Schema::Tuple(&[{}])",
73            items.iter().map(schema_expr).collect::<Vec<_>>().join(", ")
74        ),
75        Ty::Num => "wire::Schema::Num".into(),
76        Ty::Str16 => "wire::Schema::Str16".into(),
77        Ty::OptJs { inner, .. } => format!("wire::Schema::OptJs(&{})", schema_expr(inner)),
78        Ty::Obj(fields) => format!(
79            "wire::Schema::Obj(&[{}])",
80            fields
81                .iter()
82                .map(|(key, t)| format!("({key:?}, {})", schema_expr(t)))
83                .collect::<Vec<_>>()
84                .join(", ")
85        ),
86        Ty::Map16(value) => format!("wire::Schema::Map16(&{})", schema_expr(value)),
87        Ty::Dyn => "wire::Schema::Dyn".into(),
88    }
89}
90
91fn generic_arg<'a>(rust: &'a str, head: &str) -> Option<&'a str> {
92    let rust = rust.trim();
93    let rest = rust
94        .strip_prefix(head)
95        .or_else(|| rust.strip_prefix(&format!("std::collections::{head}")))?;
96    rest.strip_prefix('<')?.strip_suffix('>').map(str::trim)
97}
98
99fn map_value(rust: &str) -> Option<&str> {
100    for head in ["HashMap", "BTreeMap", "IndexMap"] {
101        if let Some(args) = generic_arg(rust, head) {
102            let (key, value) = args.split_once(',')?;
103            return (key.trim() == "String").then_some(value.trim());
104        }
105    }
106    None
107}
108
109fn is_value(rust: &str) -> bool {
110    matches!(rust.trim(), "serde_json::Value" | "Value")
111}
112
113/// A closure body: `r.f64()` stays as is, anything else is wrapped in `Ok(...)`.
114fn body(read: &str) -> String {
115    match read.strip_suffix('?') {
116        Some(call) if !call.contains('?') => call.to_string(),
117        _ => format!("Ok({read})"),
118    }
119}
120
121/// A schema as an argument: `&S` for a static, `S.inner()` (already a reference) as is.
122fn schema_ref(schema: &str) -> String {
123    if schema.ends_with(')') {
124        schema.to_string()
125    } else {
126        format!("&{schema}")
127    }
128}
129
130/// Rust code reading a value of `t` into the port type `rust` from reader `r`; `None` when the
131/// port type does not fit the wire type (the function then keeps the JSON bridge).
132pub fn rust_read(t: &Ty, rust: &str, schema: &str) -> Option<String> {
133    if is_value(rust) {
134        return Some(format!("wire::read_value(r, {})?", schema_ref(schema)));
135    }
136    let rust = rust.trim();
137    if *t == Ty::Dyn
138        && matches!(
139            rust.split_whitespace().collect::<String>().as_str(),
140            "Option<Value>" | "Option<serde_json::Value>"
141        )
142    {
143        return Some("wire::read_dyn_opt(r)?".into());
144    }
145    if *t == Ty::Dyn {
146        // Any JS value into a typed port parameter: through a tagged value and serde.
147        return Some(
148            "serde_json::from_value(wire::read_dyn(r)?).map_err(|e| format!(\"TypeError: {e}\"))?"
149                .into(),
150        );
151    }
152    let structural = rust_read_structural(t, rust, schema);
153    if structural.is_none() && rust.contains("Value") {
154        return Some(format!(
155            "serde_json::from_value(wire::read_value(r, {})?).map_err(|e| format!(\"TypeError: {{e}}\"))?",
156            schema_ref(schema)
157        ));
158    }
159    structural
160}
161
162fn rust_read_structural(t: &Ty, rust: &str, schema: &str) -> Option<String> {
163    Some(match t {
164        Ty::I64(_) if rust == "i64" => "r.i64()?".into(),
165        Ty::F64(_) if rust == "f64" => "r.f64()?".into(),
166        Ty::Bool if rust == "bool" => "r.bool()?".into(),
167        Ty::Str if rust == "String" => "r.string()?".into(),
168        Ty::Opt { inner, .. } => match generic_arg(rust, "Option") {
169            Some(inner_rust) => format!(
170                "r.opt(|r| {})?",
171                body(&rust_read(inner, inner_rust, &format!("{schema}.inner()"))?)
172            ),
173            None => format!(
174                "r.required(|r| {})?",
175                body(&rust_read(inner, rust, &format!("{schema}.inner()"))?)
176            ),
177        },
178        Ty::List { item, .. } => format!(
179            "r.list(|r| {})?",
180            body(&rust_read(
181                item,
182                generic_arg(rust, "Vec")?,
183                &format!("{schema}.inner()")
184            )?)
185        ),
186        Ty::Map { value, .. } => format!(
187            "r.map(|r| {})?.into_iter().collect()",
188            body(&rust_read(
189                value,
190                map_value(rust)?,
191                &format!("{schema}.inner()")
192            )?)
193        ),
194        Ty::Num if rust == "f64" => "r.f64()?".into(),
195        Ty::Str16 if rust == "String" => "r.string16()?".into(),
196        Ty::Str16 if rust == "Vec<u16>" => "r.units()?".into(),
197        Ty::OptJs { inner, .. } => match generic_arg(rust, "Option") {
198            Some(inner_rust) => format!(
199                "r.opt_js(|r| {})?",
200                body(&rust_read(inner, inner_rust, &format!("{schema}.inner()"))?)
201            ),
202            None => format!(
203                "r.required_js(|r| {})?",
204                body(&rust_read(inner, rust, &format!("{schema}.inner()"))?)
205            ),
206        },
207        Ty::Map16(value) => format!(
208            "r.map16(|r| {})?.into_iter().collect()",
209            body(&rust_read(
210                value,
211                map_value(rust)?,
212                &format!("{schema}.inner()")
213            )?)
214        ),
215        _ => return None,
216    })
217}
218
219/// Rust statements writing `expr` (a reference to the port type `rust`) as `t` into writer `w`.
220pub fn rust_write(t: &Ty, rust: &str, expr: &str, schema: &str, depth: usize) -> Option<String> {
221    if is_value(rust) {
222        return Some(format!(
223            "wire::write_value(w, {expr}, {})?;",
224            schema_ref(schema)
225        ));
226    }
227    if *t == Ty::Dyn {
228        return Some(format!(
229            "wire::write_dyn(w, &serde_json::to_value({expr}).map_err(|e| e.to_string())?);"
230        ));
231    }
232    if rust.contains("Value") {
233        if let Some(code) = rust_write_structural(t, rust, expr, schema, depth) {
234            return Some(code);
235        }
236        return Some(format!(
237            "wire::write_value(w, &serde_json::to_value({expr}).map_err(|e| e.to_string())?, {})?;",
238            schema_ref(schema)
239        ));
240    }
241    rust_write_structural(t, rust, expr, schema, depth)
242}
243
244fn rust_write_structural(
245    t: &Ty,
246    rust: &str,
247    expr: &str,
248    schema: &str,
249    depth: usize,
250) -> Option<String> {
251    let rust = rust.trim();
252    let x = format!("x{depth}");
253    // A method receiver: `out` as is, `&out` in parentheses.
254    let r = if expr.starts_with('&') {
255        format!("({expr})")
256    } else {
257        expr.to_string()
258    };
259    Some(match t {
260        Ty::I64(_) if rust == "i64" => format!("w.i64(*{expr});"),
261        Ty::F64(_) if rust == "f64" => format!("w.f64(*{expr});"),
262        Ty::Bool if rust == "bool" => format!("w.bool(*{expr});"),
263        Ty::Str if rust == "String" => format!("w.string({expr});"),
264        Ty::Opt { inner, .. } => {
265            let inner_schema = format!("{schema}.inner()");
266            match generic_arg(rust, "Option") {
267                Some(inner_rust) => format!(
268                    "match {expr} {{ Some({x}) => {{ w.tag(1); {} }} None => w.tag(0) }}",
269                    rust_write(inner, inner_rust, &x, &inner_schema, depth + 1)?
270                ),
271                None => format!(
272                    "w.tag(1); {}",
273                    rust_write(inner, rust, expr, &inner_schema, depth + 1)?
274                ),
275            }
276        }
277        Ty::List { item, .. } => format!(
278            "w.tag(1); w.count({r}.len()); for {x} in {r}.iter() {{ {} }}",
279            rust_write(
280                item,
281                generic_arg(rust, "Vec")?,
282                &x,
283                &format!("{schema}.inner()"),
284                depth + 1
285            )?
286        ),
287        Ty::Map { value, .. } => format!(
288            "w.tag(1); w.count({r}.len()); for (k{depth}, {x}) in {r}.iter() {{ w.string(k{depth}); {} }}",
289            rust_write(
290                value,
291                map_value(rust)?,
292                &x,
293                &format!("{schema}.inner()"),
294                depth + 1
295            )?
296        ),
297        Ty::Num if rust == "f64" => format!("w.f64(*{expr});"),
298        Ty::Str16 if rust == "String" => format!("w.string16({expr});"),
299        Ty::Str16 if rust == "Vec<u16>" => format!("w.units({expr});"),
300        Ty::OptJs {
301            inner, undefinable, ..
302        } => {
303            let inner_schema = format!("{schema}.inner()");
304            // `None` is `undefined`, or `null` for a `T | null` that cannot be undefined.
305            let none = if *undefinable { 0 } else { 2 };
306            match generic_arg(rust, "Option") {
307                Some(inner_rust) => format!(
308                    "match {expr} {{ Some({x}) => {{ w.tag(1); {} }} None => w.tag({none}) }}",
309                    rust_write(inner, inner_rust, &x, &inner_schema, depth + 1)?
310                ),
311                None => format!(
312                    "w.tag(1); {}",
313                    rust_write(inner, rust, expr, &inner_schema, depth + 1)?
314                ),
315            }
316        }
317        Ty::Map16(value) => format!(
318            "w.tag(1); w.count({r}.len()); for (k{depth}, {x}) in {r}.iter() {{ w.string16(k{depth}); {} }}",
319            rust_write(
320                value,
321                map_value(rust)?,
322                &x,
323                &format!("{schema}.inner()"),
324                depth + 1
325            )?
326        ),
327        _ => return None,
328    })
329}
330
331/// `src/wire.rs` of a generated crate: the reader, the writer, and schema-driven conversion of
332/// `serde_json::Value` (for ports that keep structured values as JSON values).
333pub const WIRE_RS: &str = r#"//! The binary wire between the source language and the port. Generated by rust-anything.
334
335#![forbid(unsafe_code)]
336#![allow(dead_code)]
337
338use serde_json::{Map, Value, json};
339
340/// A wire type, for converting `serde_json::Value`s.
341pub enum Schema {
342    I64,
343    F64,
344    Bool,
345    Str,
346    List(&'static Schema),
347    Map(&'static Schema),
348    Opt(&'static Schema),
349    Struct(&'static [(&'static str, Schema)]),
350    Tuple(&'static [Schema]),
351    Num,
352    Str16,
353    OptJs(&'static Schema),
354    Obj(&'static [(&'static str, Schema)]),
355    Map16(&'static Schema),
356    Dyn,
357}
358
359impl Schema {
360    /// The item type of a list, map or option.
361    pub const fn inner(&self) -> &Schema {
362        match self {
363            Self::List(s) | Self::Map(s) | Self::Opt(s) | Self::OptJs(s) | Self::Map16(s) => s,
364            _ => self,
365        }
366    }
367}
368
369pub struct Reader<'a> {
370    bytes: &'a [u8],
371    at: usize,
372}
373
374const SHORT: &str = "TypeError: wire data ended early";
375
376impl<'a> Reader<'a> {
377    pub fn new(bytes: &'a [u8]) -> Self {
378        Self { bytes, at: 0 }
379    }
380
381    fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
382        let end = self.at.checked_add(n).filter(|&e| e <= self.bytes.len()).ok_or(SHORT)?;
383        let out = &self.bytes[self.at..end];
384        self.at = end;
385        Ok(out)
386    }
387
388    pub fn tag(&mut self) -> Result<u8, String> {
389        Ok(self.take(1)?[0])
390    }
391
392    pub fn count(&mut self) -> Result<usize, String> {
393        let b = self.take(4)?;
394        Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize)
395    }
396
397    pub fn i64(&mut self) -> Result<i64, String> {
398        let b = self.take(8)?;
399        Ok(i64::from_le_bytes(b.try_into().map_err(|_| SHORT)?))
400    }
401
402    pub fn f64(&mut self) -> Result<f64, String> {
403        let b = self.take(8)?;
404        Ok(f64::from_le_bytes(b.try_into().map_err(|_| SHORT)?))
405    }
406
407    pub fn bool(&mut self) -> Result<bool, String> {
408        Ok(self.tag()? != 0)
409    }
410
411    /// A string; `None` for null.
412    pub fn opt_string(&mut self) -> Result<Option<String>, String> {
413        if self.tag()? == 0 {
414            return Ok(None);
415        }
416        let n = self.count()?;
417        Ok(Some(String::from_utf8_lossy(self.take(n)?).into_owned()))
418    }
419
420    pub fn string(&mut self) -> Result<String, String> {
421        self.opt_string()?
422            .ok_or_else(|| "NullPointerException: null string".to_string())
423    }
424
425    pub fn opt<T>(&mut self, item: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<Option<T>, String> {
426        if self.tag()? == 0 { Ok(None) } else { item(self).map(Some) }
427    }
428
429    pub fn required<T>(&mut self, item: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
430        self.opt(item)?
431            .ok_or_else(|| "NullPointerException: null value".to_string())
432    }
433
434    /// A JS string as UTF-16 code units.
435    pub fn units(&mut self) -> Result<Vec<u16>, String> {
436        if self.tag()? == 0 {
437            return Err("TypeError: expected a string".into());
438        }
439        let n = self.count()?;
440        let bytes = self.take(n.checked_mul(2).ok_or(SHORT)?)?;
441        Ok(bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect())
442    }
443
444    /// A JS string; lone surrogates become U+FFFD, as napi's own conversion does.
445    pub fn string16(&mut self) -> Result<String, String> {
446        Ok(String::from_utf16_lossy(&self.units()?))
447    }
448
449    /// A JS optional value: 0 `undefined`, 1 a value, 2 `null`.
450    pub fn opt_js<T>(&mut self, item: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<Option<T>, String> {
451        if self.tag()? == 1 { item(self).map(Some) } else { Ok(None) }
452    }
453
454    pub fn required_js<T>(&mut self, item: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
455        self.opt_js(item)?
456            .ok_or_else(|| "TypeError: expected a value, got undefined or null".to_string())
457    }
458
459    /// A string-keyed record (keys as JS strings).
460    pub fn map16<T>(&mut self, mut item: impl FnMut(&mut Self) -> Result<T, String>) -> Result<Vec<(String, T)>, String> {
461        if self.tag()? == 0 {
462            return Ok(Vec::new());
463        }
464        let n = self.count()?;
465        let mut out = Vec::with_capacity(n.min(1 << 16));
466        for _ in 0..n {
467            let key = self.string16()?;
468            out.push((key, item(self)?));
469        }
470        Ok(out)
471    }
472
473    /// A list; nil reads as empty.
474    pub fn list<T>(&mut self, mut item: impl FnMut(&mut Self) -> Result<T, String>) -> Result<Vec<T>, String> {
475        if self.tag()? == 0 {
476            return Ok(Vec::new());
477        }
478        let n = self.count()?;
479        let mut out = Vec::with_capacity(n.min(1 << 16));
480        for _ in 0..n {
481            out.push(item(self)?);
482        }
483        Ok(out)
484    }
485
486    /// A map's entries; nil reads as empty.
487    pub fn map<T>(&mut self, mut item: impl FnMut(&mut Self) -> Result<T, String>) -> Result<Vec<(String, T)>, String> {
488        if self.tag()? == 0 {
489            return Ok(Vec::new());
490        }
491        let n = self.count()?;
492        let mut out = Vec::with_capacity(n.min(1 << 16));
493        for _ in 0..n {
494            let key = self.string()?;
495            out.push((key, item(self)?));
496        }
497        Ok(out)
498    }
499}
500
501#[derive(Default)]
502pub struct Writer(pub Vec<u8>);
503
504impl Writer {
505    pub fn tag(&mut self, t: u8) {
506        self.0.push(t);
507    }
508
509    pub fn count(&mut self, n: usize) {
510        self.0.extend_from_slice(&u32::try_from(n).unwrap_or(u32::MAX).to_le_bytes());
511    }
512
513    pub fn i64(&mut self, v: i64) {
514        self.0.extend_from_slice(&v.to_le_bytes());
515    }
516
517    pub fn f64(&mut self, v: f64) {
518        self.0.extend_from_slice(&v.to_le_bytes());
519    }
520
521    pub fn bool(&mut self, v: bool) {
522        self.0.push(u8::from(v));
523    }
524
525    pub fn string(&mut self, s: &str) {
526        self.tag(1);
527        self.count(s.len());
528        self.0.extend_from_slice(s.as_bytes());
529    }
530
531    /// A JS string from a Rust one (well-formed: tag 1).
532    pub fn string16(&mut self, s: &str) {
533        self.tag(1);
534        let at = self.0.len();
535        self.count(0);
536        let mut n = 0usize;
537        for u in s.encode_utf16() {
538            self.0.extend_from_slice(&u.to_le_bytes());
539            n += 1;
540        }
541        self.0[at..at + 4].copy_from_slice(&u32::try_from(n).unwrap_or(u32::MAX).to_le_bytes());
542    }
543
544    /// A JS string from code units, lone surrogates included (tag 4).
545    pub fn units(&mut self, units: &[u16]) {
546        self.tag(4);
547        self.count(units.len());
548        for u in units {
549            self.0.extend_from_slice(&u.to_le_bytes());
550        }
551    }
552}
553
554fn float_value(x: f64) -> Value {
555    if x.is_nan() {
556        json!({"$num": "NaN"})
557    } else if x.is_infinite() {
558        json!({"$num": if x > 0.0 { "Infinity" } else { "-Infinity" }})
559    } else if x == 0.0 && x.is_sign_negative() {
560        json!({"$num": "-0"})
561    } else {
562        json!(x)
563    }
564}
565
566fn value_float(v: &Value) -> Option<f64> {
567    match v {
568        Value::Number(n) => n.as_f64(),
569        Value::Object(o) => match o.get("$num")?.as_str()? {
570            "NaN" => Some(f64::NAN),
571            "Infinity" => Some(f64::INFINITY),
572            "-Infinity" => Some(f64::NEG_INFINITY),
573            "-0" => Some(-0.0),
574            _ => None,
575        },
576        _ => None,
577    }
578}
579
580/// Reads a value of `schema` as JSON: null for nil, `{"$num": ...}` for NaN and infinities.
581pub fn read_value(r: &mut Reader, schema: &Schema) -> Result<Value, String> {
582    Ok(match schema {
583        Schema::I64 => json!(r.i64()?),
584        Schema::F64 => float_value(r.f64()?),
585        Schema::Bool => Value::Bool(r.bool()?),
586        Schema::Str => r.opt_string()?.map_or(Value::Null, Value::String),
587        Schema::Opt(inner) => r.opt(|r| read_value(r, inner))?.unwrap_or(Value::Null),
588        Schema::List(item) => {
589            if r.tag()? == 0 {
590                Value::Null
591            } else {
592                let n = r.count()?;
593                let mut out = Vec::with_capacity(n.min(1 << 16));
594                for _ in 0..n {
595                    out.push(read_value(r, item)?);
596                }
597                Value::Array(out)
598            }
599        }
600        Schema::Map(item) => {
601            if r.tag()? == 0 {
602                Value::Null
603            } else {
604                let n = r.count()?;
605                let mut out = Map::new();
606                for _ in 0..n {
607                    let key = r.string()?;
608                    out.insert(key, read_value(r, item)?);
609                }
610                Value::Object(out)
611            }
612        }
613        Schema::Struct(fields) => {
614            if r.tag()? == 0 {
615                Value::Null
616            } else {
617                let mut out = Map::new();
618                for (key, field) in *fields {
619                    out.insert((*key).to_string(), read_value(r, field)?);
620                }
621                Value::Object(out)
622            }
623        }
624        Schema::Tuple(items) => Value::Array(items.iter().map(|s| read_value(r, s)).collect::<Result<_, _>>()?),
625        Schema::Num => js_number(r.f64()?),
626        Schema::Str16 => js_string(r.units()?),
627        Schema::OptJs(inner) => match r.tag()? {
628            1 => read_value(r, inner)?,
629            2 => Value::Null,
630            _ => json!({"$undefined": true}),
631        },
632        Schema::Obj(fields) => {
633            let n = r.tag()?;
634            let mut out = Map::new();
635            for _ in 0..n {
636                let index = usize::from(r.tag()?);
637                match fields.get(index) {
638                    Some((key, field)) => {
639                        out.insert((*key).to_string(), read_value(r, field)?);
640                    }
641                    None => {
642                        let key = r.string16()?;
643                        out.insert(key, read_dyn(r)?);
644                    }
645                }
646            }
647            Value::Object(out)
648        }
649        Schema::Map16(item) => {
650            if r.tag()? == 0 {
651                Value::Null
652            } else {
653                let n = r.count()?;
654                let mut out = Map::new();
655                for _ in 0..n {
656                    let key = r.string16()?;
657                    out.insert(key, read_value(r, item)?);
658                }
659                Value::Object(out)
660            }
661        }
662        Schema::Dyn => read_dyn(r)?,
663    })
664}
665
666/// A JS number as JSON, as the JSON bridge reads it: integers as integers, markers for the rest.
667fn js_number(x: f64) -> Value {
668    if x.is_finite() && !(x == 0.0 && x.is_sign_negative()) && x.fract() == 0.0 && x.abs() < 9_007_199_254_740_992.0 {
669        json!(x as i64)
670    } else {
671        float_value(x)
672    }
673}
674
675/// A JS string as JSON: lone surrogates as `{"$utf16": [...]}`.
676fn js_string(units: Vec<u16>) -> Value {
677    match String::from_utf16(&units) {
678        Ok(s) => Value::String(s),
679        Err(_) => json!({"$utf16": units}),
680    }
681}
682
683/// Any JS value, tagged: 0 undefined, 1 null, 2 false, 3 true, 4 number, 5 string, 6 array,
684/// 7 object.
685/// An optional JS value: `undefined` and `null` are `None`, as JSON gives for an `Option`.
686pub fn read_dyn_opt(r: &mut Reader) -> Result<Option<Value>, String> {
687    if matches!(r.bytes.get(r.at), Some(0 | 1)) {
688        r.at += 1;
689        return Ok(None);
690    }
691    read_dyn(r).map(Some)
692}
693
694pub fn read_dyn(r: &mut Reader) -> Result<Value, String> {
695    let units = |r: &mut Reader| -> Result<Vec<u16>, String> {
696        let n = r.count()?;
697        let bytes = r.take(n.checked_mul(2).ok_or(SHORT)?)?;
698        Ok(bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect())
699    };
700    Ok(match r.tag()? {
701        0 => json!({"$undefined": true}),
702        1 => Value::Null,
703        2 => Value::Bool(false),
704        3 => Value::Bool(true),
705        4 => js_number(r.f64()?),
706        5 => js_string(units(r)?),
707        6 => {
708            let n = r.count()?;
709            let mut out = Vec::with_capacity(n.min(1 << 16));
710            for _ in 0..n {
711                out.push(read_dyn(r)?);
712            }
713            Value::Array(out)
714        }
715        7 => {
716            let n = r.count()?;
717            let mut out = Map::new();
718            for _ in 0..n {
719                let key = String::from_utf16_lossy(&units(r)?);
720                out.insert(key, read_dyn(r)?);
721            }
722            Value::Object(out)
723        }
724        t => return Err(format!("TypeError: unknown value tag {t}")),
725    })
726}
727
728fn marker<'v>(v: &'v Value, key: &str) -> Option<&'v Value> {
729    v.as_object().filter(|o| o.len() == 1).and_then(|o| o.get(key))
730}
731
732fn write_units16(w: &mut Writer, v: &Value) -> Option<()> {
733    if let Value::String(s) = v {
734        w.string16(s);
735        return Some(());
736    }
737    let units: Vec<u16> = marker(v, "$utf16")?
738        .as_array()?
739        .iter()
740        .map(|u| u.as_u64().and_then(|u| u16::try_from(u).ok()))
741        .collect::<Option<_>>()?;
742    w.units(&units);
743    Some(())
744}
745
746/// Writes any JSON value as a tagged JS value; markers become what they stand for.
747pub fn write_dyn(w: &mut Writer, v: &Value) {
748    match v {
749        Value::Null => w.tag(1),
750        Value::Bool(b) => w.tag(if *b { 3 } else { 2 }),
751        Value::Number(n) => {
752            w.tag(4);
753            w.f64(n.as_f64().unwrap_or(f64::NAN));
754        }
755        Value::String(s) => {
756            w.tag(5);
757            let units: Vec<u16> = s.encode_utf16().collect();
758            w.count(units.len());
759            for u in units {
760                w.0.extend_from_slice(&u.to_le_bytes());
761            }
762        }
763        Value::Array(items) => {
764            w.tag(6);
765            w.count(items.len());
766            for x in items {
767                write_dyn(w, x);
768            }
769        }
770        Value::Object(o) => {
771            if marker(v, "$undefined").is_some() {
772                w.tag(0);
773            } else if let Some(x) = value_float(v).filter(|_| marker(v, "$num").is_some()) {
774                w.tag(4);
775                w.f64(x);
776            } else if let Some(units) = marker(v, "$utf16").and_then(Value::as_array) {
777                w.tag(5);
778                w.count(units.len());
779                for u in units {
780                    w.0.extend_from_slice(&u16::try_from(u.as_u64().unwrap_or(0xFFFD)).unwrap_or(0xFFFD).to_le_bytes());
781                }
782            } else {
783                w.tag(7);
784                w.count(o.len());
785                for (k, x) in o {
786                    let units: Vec<u16> = k.encode_utf16().collect();
787                    w.count(units.len());
788                    for u in units {
789                        w.0.extend_from_slice(&u.to_le_bytes());
790                    }
791                    write_dyn(w, x);
792                }
793            }
794        }
795    }
796}
797
798/// The start of the error a result of the wrong shape raises; JS bridges answer it by running
799/// the call through JSON instead.
800pub const MISMATCH: &str = "TypeError: the port returned ";
801
802fn mismatch(schema: &str, v: &Value) -> String {
803    format!("{MISMATCH}{v} where the original returns {schema}")
804}
805
806/// Writes a JSON value as `schema`; the port's value must fit the original's type.
807pub fn write_value(w: &mut Writer, v: &Value, schema: &Schema) -> Result<(), String> {
808    match schema {
809        Schema::I64 => w.i64(v.as_i64().or_else(|| v.as_f64().filter(|f| f.fract() == 0.0).map(|f| f as i64)).ok_or_else(|| mismatch("an integer", v))?),
810        Schema::F64 => w.f64(value_float(v).ok_or_else(|| mismatch("a float", v))?),
811        Schema::Bool => w.bool(v.as_bool().ok_or_else(|| mismatch("a bool", v))?),
812        Schema::Str => match v {
813            Value::Null => w.tag(0),
814            Value::String(s) => w.string(s),
815            _ => return Err(mismatch("a string", v)),
816        },
817        Schema::Opt(inner) => {
818            if v.is_null() {
819                w.tag(0);
820            } else {
821                w.tag(1);
822                write_value(w, v, inner)?;
823            }
824        }
825        Schema::List(item) => match v {
826            Value::Null => w.tag(0),
827            Value::Array(items) => {
828                w.tag(1);
829                w.count(items.len());
830                for x in items {
831                    write_value(w, x, item)?;
832                }
833            }
834            _ => return Err(mismatch("a list", v)),
835        },
836        Schema::Map(item) => match v {
837            Value::Null => w.tag(0),
838            Value::Object(o) => {
839                w.tag(1);
840                w.count(o.len());
841                for (k, x) in o {
842                    w.string(k);
843                    write_value(w, x, item)?;
844                }
845            }
846            _ => return Err(mismatch("a map", v)),
847        },
848        Schema::Struct(fields) => match v {
849            Value::Null => w.tag(0),
850            Value::Object(o) => {
851                w.tag(1);
852                for (key, field) in *fields {
853                    write_value(w, o.get(*key).unwrap_or(&Value::Null), field)?;
854                }
855            }
856            _ => return Err(mismatch("a struct", v)),
857        },
858        Schema::Tuple(items) => match v {
859            Value::Array(values) if values.len() == items.len() => {
860                for (x, s) in values.iter().zip(*items) {
861                    write_value(w, x, s)?;
862                }
863            }
864            _ => return Err(mismatch("several results", v)),
865        },
866        Schema::Num => w.f64(value_float(v).ok_or_else(|| mismatch("a number", v))?),
867        Schema::Str16 => write_units16(w, v).ok_or_else(|| mismatch("a string", v))?,
868        Schema::OptJs(inner) => {
869            if marker(v, "$undefined").is_some() {
870                w.tag(0);
871            } else if v.is_null() {
872                w.tag(2);
873            } else {
874                w.tag(1);
875                write_value(w, v, inner)?;
876            }
877        }
878        Schema::Obj(fields) => {
879            let o = v.as_object().ok_or_else(|| mismatch("an object", v))?;
880            w.tag(u8::try_from(o.len()).map_err(|_| mismatch("an object of at most 255 keys", v))?);
881            for (k, x) in o {
882                match fields.iter().position(|(key, _)| key == k) {
883                    Some(i) if i < 255 => {
884                        w.tag(i as u8);
885                        write_value(w, x, &fields[i].1)?;
886                    }
887                    _ => {
888                        w.tag(255);
889                        w.string16(k);
890                        write_dyn(w, x);
891                    }
892                }
893            }
894        }
895        Schema::Map16(item) => match v {
896            Value::Null => w.tag(0),
897            Value::Object(o) => {
898                w.tag(1);
899                w.count(o.len());
900                for (k, x) in o {
901                    w.string16(k);
902                    write_value(w, x, item)?;
903                }
904            }
905            _ => return Err(mismatch("a record", v)),
906        },
907        Schema::Dyn => write_dyn(w, v),
908    }
909    Ok(())
910}
911"#;
912
913/// Rust statements that read every argument of a port function from `r`; `None` when one does
914/// not fit.
915pub fn rust_read_args(
916    params: &[(String, Ty)],
917    port_params: &[(String, String)],
918    schema_prefix: &str,
919    statics: &mut String,
920) -> Option<String> {
921    let mut out = String::new();
922    for (i, ((_, ty), (name, rust))) in params.iter().zip(port_params).enumerate() {
923        let schema = format!("{schema_prefix}_{i}");
924        let read = rust_read(ty, rust, &schema)?;
925        if read.contains(&schema) {
926            let _ = writeln!(
927                statics,
928                "static {schema}: wire::Schema = {};",
929                schema_expr(ty)
930            );
931        }
932        let _ = writeln!(out, "        let {name}: {rust} = {read};");
933    }
934    Some(out)
935}
936
937#[cfg(test)]
938mod tests {
939    use super::*;
940
941    fn list(item: Ty) -> Ty {
942        Ty::List {
943            item: Box::new(item),
944            native: String::new(),
945            array: false,
946        }
947    }
948
949    #[test]
950    fn reads_fit_the_port_types() {
951        let strings = list(Ty::Str);
952        assert_eq!(
953            rust_read(&strings, "Vec<String>", "S").unwrap(),
954            "r.list(|r| r.string())?"
955        );
956        let boxed = Ty::Opt {
957            inner: Box::new(Ty::I64("int".into())),
958            native: "Integer".into(),
959        };
960        assert_eq!(
961            rust_read(&boxed, "i64", "S").unwrap(),
962            "r.required(|r| r.i64())?"
963        );
964        assert_eq!(
965            rust_read(&boxed, "Option<i64>", "S").unwrap(),
966            "r.opt(|r| r.i64())?"
967        );
968        assert_eq!(
969            rust_read(&strings, "serde_json::Value", "S").unwrap(),
970            "wire::read_value(r, &S)?"
971        );
972        // A port type that does not fit the wire type keeps the JSON bridge.
973        assert!(rust_read(&strings, "Vec<i64>", "S").is_none());
974    }
975
976    #[test]
977    fn writes_fit_the_port_types() {
978        let floats = list(Ty::F64("double".into()));
979        assert_eq!(
980            rust_write(&floats, "Vec<f64>", "out", "S", 0).unwrap(),
981            "w.tag(1); w.count(out.len()); for x0 in out.iter() { w.f64(*x0); }"
982        );
983        assert_eq!(
984            schema_expr(&floats),
985            "wire::Schema::List(&wire::Schema::F64)"
986        );
987    }
988}