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