catlog_wasm/
wd.rs

1//! Serialization of wiring diagrams.
2
3use serde::{Deserialize, Serialize};
4use tsify::Tsify;
5
6use catlog::wd;
7use catlog::zero::{LabelSegment, NameSegment, QualifiedName};
8
9/// An undirected wiring diagram.
10///
11/// For now, junctions are assumed to be qualified names as that's all we need.
12#[derive(Serialize, Deserialize, Tsify)]
13#[tsify(into_wasm_abi, from_wasm_abi)]
14pub struct UWD {
15    /// Outer ports of diagram.
16    #[serde(rename = "outerPorts")]
17    pub outer_ports: Vec<UWDPort>,
18
19    /// Boxes in diagram.
20    pub boxes: Vec<UWDBox>,
21
22    /// Junctions in diagram.
23    pub junctions: Vec<QualifiedName>,
24}
25
26/// A box in an undirected wiring diagram.
27#[derive(Serialize, Deserialize, Tsify)]
28#[tsify(into_wasm_abi, from_wasm_abi)]
29pub struct UWDBox {
30    /// Identifier of box, unique within diagram.
31    pub name: NameSegment,
32
33    /// Human-readlable label for box.
34    pub label: LabelSegment,
35
36    /// Ports of box.
37    pub ports: Vec<UWDPort>,
38}
39
40/// A port in an undirected wiring diagram.
41///
42/// The type of the port is omitted.
43#[derive(Serialize, Deserialize, Tsify)]
44#[tsify(into_wasm_abi, from_wasm_abi, missing_as_null)]
45pub struct UWDPort {
46    /// Identifier of port, unique among an interface (list of ports).
47    pub name: NameSegment,
48
49    /// Human-readable label for port.
50    pub label: LabelSegment,
51
52    /// The junction that the port is assigned to, if any.
53    pub junction: Option<QualifiedName>,
54}
55
56/// Serializes an undirected wiring diagram.
57pub fn serialize_uwd<T: Clone + Eq>(uwd: &wd::UWD<T, QualifiedName>) -> UWD {
58    let outer_ports = uwd
59        .outer_ports()
60        .iter()
61        .map(|(&name, &(label, _))| UWDPort {
62            name,
63            label,
64            junction: uwd.get_outer(name).cloned(),
65        })
66        .collect();
67
68    let boxes = uwd
69        .boxes()
70        .map(|(&box_name, &box_label, ports)| UWDBox {
71            name: box_name,
72            label: box_label,
73            ports: ports
74                .iter()
75                .map(|(&port_name, &(port_label, _))| UWDPort {
76                    name: port_name,
77                    label: port_label,
78                    junction: uwd.get(box_name, port_name).cloned(),
79                })
80                .collect(),
81        })
82        .collect();
83
84    let junctions = uwd.junctions().collect();
85
86    UWD { outer_ports, boxes, junctions }
87}