Skip to main content

astrs_wire/ids/
port.rs

1//! [`PortRef`] — one endpoint of a graph edge.
2//!
3//! A manifest input is written `node/output` in its short form (blueprint
4//! §8.3), and that is exactly what a `PortRef` denotes: the node that owns the
5//! port and the port's own id. Because neither [`NodeId`] nor [`DataId`]
6//! admits `/`, the text form parses unambiguously by splitting on the single
7//! separator.
8//!
9//! # Examples
10//!
11//! ```
12//! use astrs_wire::PortRef;
13//!
14//! let port: PortRef = "camera/image".parse()?;
15//! assert_eq!(port.node().as_str(), "camera");
16//! assert_eq!(port.port().as_str(), "image");
17//! assert_eq!(port.to_string(), "camera/image");
18//! # Ok::<(), astrs_wire::IdError>(())
19//! ```
20
21use core::fmt;
22use core::str::FromStr;
23
24use oxicode::{Decode, Encode};
25use serde::{Deserialize, Deserializer, Serialize};
26
27use crate::error::{IdError, IdKind, preview};
28use crate::ids::name::{DataId, NodeId};
29
30/// The separator between the node id and the port id in the text form.
31pub const PORT_REF_SEPARATOR: char = '/';
32
33/// A reference to one input or output port of one node.
34///
35/// # Examples
36///
37/// ```
38/// use astrs_wire::{DataId, NodeId, PortRef};
39///
40/// let port = PortRef::new(NodeId::new("detector")?, DataId::new("boxes")?);
41/// assert_eq!(port.to_string(), "detector/boxes");
42/// assert_eq!("detector/boxes".parse::<PortRef>()?, port);
43/// # Ok::<(), astrs_wire::IdError>(())
44/// ```
45#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Encode, Decode)]
46pub struct PortRef {
47    /// The node that owns the port.
48    node: NodeId,
49    /// The port's own id.
50    port: DataId,
51}
52
53impl PortRef {
54    /// Builds a port reference from its two halves.
55    #[must_use]
56    pub const fn new(node: NodeId, port: DataId) -> Self {
57        Self { node, port }
58    }
59
60    /// Builds a port reference from unvalidated strings.
61    ///
62    /// # Errors
63    ///
64    /// [`IdError`] if either half fails its grammar.
65    ///
66    /// # Examples
67    ///
68    /// ```
69    /// use astrs_wire::PortRef;
70    ///
71    /// assert!(PortRef::from_parts("camera", "image").is_ok());
72    /// assert!(PortRef::from_parts("camera", "im age").is_err());
73    /// ```
74    pub fn from_parts(node: &str, port: &str) -> Result<Self, IdError> {
75        Ok(Self {
76            node: NodeId::new(node)?,
77            port: DataId::new(port)?,
78        })
79    }
80
81    /// The node that owns the port.
82    #[must_use]
83    pub const fn node(&self) -> &NodeId {
84        &self.node
85    }
86
87    /// The port's own id.
88    #[must_use]
89    pub const fn port(&self) -> &DataId {
90        &self.port
91    }
92
93    /// Consumes the reference and returns its two halves.
94    #[must_use]
95    pub fn into_parts(self) -> (NodeId, DataId) {
96        (self.node, self.port)
97    }
98}
99
100impl fmt::Display for PortRef {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        write!(f, "{}{PORT_REF_SEPARATOR}{}", self.node, self.port)
103    }
104}
105
106impl fmt::Debug for PortRef {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        write!(f, "PortRef({self})")
109    }
110}
111
112impl FromStr for PortRef {
113    type Err = IdError;
114
115    /// Parses the `node/port` short form.
116    ///
117    /// # Errors
118    ///
119    /// [`IdError::Malformed`] when there is no separator or more than one;
120    /// [`IdError`] from the halves' own validation otherwise.
121    fn from_str(text: &str) -> Result<Self, Self::Err> {
122        let malformed = |reason: &'static str| IdError::Malformed {
123            kind: IdKind::Name,
124            value: preview(text),
125            reason,
126        };
127        let (node, port) = text
128            .split_once(PORT_REF_SEPARATOR)
129            .ok_or_else(|| malformed("expected the form `node/port`"))?;
130        if port.contains(PORT_REF_SEPARATOR) {
131            return Err(malformed("more than one '/' in a port reference"));
132        }
133        Self::from_parts(node, port)
134    }
135}
136
137impl TryFrom<&str> for PortRef {
138    type Error = IdError;
139
140    fn try_from(text: &str) -> Result<Self, Self::Error> {
141        text.parse()
142    }
143}
144
145impl<'de> Deserialize<'de> for PortRef {
146    /// Accepts both the short string form (`"camera/image"`) and the explicit
147    /// map form (`{"node": "camera", "port": "image"}`).
148    ///
149    /// Manifests use the short form; machine-generated JSON tends to use the
150    /// map. Accepting both keeps `--json` output round-trippable without
151    /// forcing either style on a human editor.
152    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
153        #[derive(Deserialize)]
154        #[serde(untagged)]
155        enum Repr {
156            Short(String),
157            Long {
158                /// The node that owns the port.
159                node: NodeId,
160                /// The port's own id.
161                port: DataId,
162            },
163        }
164
165        match Repr::deserialize(deserializer)? {
166            Repr::Short(text) => text.parse().map_err(serde::de::Error::custom),
167            Repr::Long { node, port } => Ok(Self { node, port }),
168        }
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
175
176    use super::*;
177    use crate::codec::{WireDecode, WireEncode};
178
179    #[test]
180    fn text_form_round_trips() {
181        for text in [
182            "camera/image",
183            "perception.detector/boxes",
184            "a/b",
185            "node-1/out_0",
186        ] {
187            let port: PortRef = text.parse().unwrap();
188            assert_eq!(port.to_string(), text);
189        }
190    }
191
192    #[test]
193    fn accessors_expose_both_halves() {
194        let port = PortRef::from_parts("camera", "image").unwrap();
195        assert_eq!(port.node().as_str(), "camera");
196        assert_eq!(port.port().as_str(), "image");
197        let (node, data) = port.clone().into_parts();
198        assert_eq!(PortRef::new(node, data), port);
199        assert_eq!(format!("{port:?}"), "PortRef(camera/image)");
200    }
201
202    #[test]
203    fn missing_or_extra_separators_are_rejected() {
204        for bad in ["camera", "camera/image/extra", "/image", "camera/"] {
205            assert!(bad.parse::<PortRef>().is_err(), "{bad:?} should fail");
206        }
207    }
208
209    #[test]
210    fn invalid_halves_are_rejected() {
211        assert!("cam era/image".parse::<PortRef>().is_err());
212        assert!("camera/im age".parse::<PortRef>().is_err());
213    }
214
215    #[test]
216    fn codec_round_trips() {
217        let port = PortRef::from_parts("planner", "path").unwrap();
218        let bytes = port.encode_to_vec().unwrap();
219        assert_eq!(PortRef::decode_exact(&bytes).unwrap(), port);
220    }
221
222    #[test]
223    fn decoding_validates_both_halves() {
224        let forged = ("bad node".to_owned(), "port".to_owned())
225            .encode_to_vec()
226            .unwrap();
227        assert!(PortRef::decode_exact(&forged).is_err());
228    }
229
230    #[test]
231    fn serde_writes_the_map_form_and_reads_both() {
232        let port = PortRef::from_parts("camera", "image").unwrap();
233        let json = serde_json::to_string(&port).unwrap();
234        assert_eq!(json, r#"{"node":"camera","port":"image"}"#);
235        assert_eq!(serde_json::from_str::<PortRef>(&json).unwrap(), port);
236        assert_eq!(
237            serde_json::from_str::<PortRef>("\"camera/image\"").unwrap(),
238            port
239        );
240        assert!(serde_json::from_str::<PortRef>("\"camera\"").is_err());
241    }
242
243    #[test]
244    fn try_from_matches_parse() {
245        assert_eq!(
246            PortRef::try_from("a/b").unwrap(),
247            "a/b".parse::<PortRef>().unwrap()
248        );
249    }
250
251    #[test]
252    fn ordering_is_by_node_then_port() {
253        let mut ports = [
254            PortRef::from_parts("b", "a").unwrap(),
255            PortRef::from_parts("a", "z").unwrap(),
256            PortRef::from_parts("a", "a").unwrap(),
257        ];
258        ports.sort();
259        assert_eq!(ports[0].to_string(), "a/a");
260        assert_eq!(ports[1].to_string(), "a/z");
261        assert_eq!(ports[2].to_string(), "b/a");
262    }
263}