Skip to main content

rustorb_dds_ros2/
names.rs

1//! ROS 2 names and their DDS names.
2//!
3//! ROS 2 (Jazzy, `rmw_fastrtps_cpp` and `rmw_cyclonedds_cpp`), seen from
4//! outside, puts on DDS:
5//!
6//! - a topic `/ns/name` as the DDS topic `rt/ns/name`;
7//! - a service `/ns/name` as the request topic `rq/ns/nameRequest` and
8//!   the reply topic `rr/ns/nameReply`;
9//! - a message type `pkg/msg/Name` as the DDS type
10//!   `pkg::msg::dds_::Name_`, and the request and response of a service
11//!   type `pkg/srv/Name` as `pkg::srv::dds_::Name_Request_` and
12//!   `pkg::srv::dds_::Name_Response_`.
13//!
14//! The rules on the names themselves are those of the ROS 2 design
15//! article "Topic and Service name mapping to DDS" and of the ROS 2
16//! documentation on names: a name is tokens of `[A-Za-z0-9_]` that do not
17//! start with a digit, separated by `/`; no empty token, no `__`, no
18//! trailing `/`. A fully qualified name starts with `/`.
19
20use std::fmt;
21
22use crate::{Error, Result};
23
24/// The prefix of the DDS topic of a ROS 2 topic.
25pub const TOPIC_PREFIX: &str = "rt";
26/// The prefix of the DDS topic of the requests of a ROS 2 service.
27pub const REQUEST_PREFIX: &str = "rq";
28/// The prefix of the DDS topic of the replies of a ROS 2 service.
29pub const REPLY_PREFIX: &str = "rr";
30/// The suffix of the DDS topic of the requests of a ROS 2 service.
31pub const REQUEST_SUFFIX: &str = "Request";
32/// The suffix of the DDS topic of the replies of a ROS 2 service.
33pub const REPLY_SUFFIX: &str = "Reply";
34
35/// The kind of an interface: a message, a service or an action.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
37pub enum InterfaceKind {
38    /// `msg`.
39    Message,
40    /// `srv`.
41    Service,
42    /// `action`.
43    Action,
44}
45
46impl InterfaceKind {
47    /// `msg`, `srv` or `action`.
48    pub fn as_str(self) -> &'static str {
49        match self {
50            InterfaceKind::Message => "msg",
51            InterfaceKind::Service => "srv",
52            InterfaceKind::Action => "action",
53        }
54    }
55
56    fn parse(s: &str) -> Option<InterfaceKind> {
57        match s {
58            "msg" => Some(InterfaceKind::Message),
59            "srv" => Some(InterfaceKind::Service),
60            "action" => Some(InterfaceKind::Action),
61            _ => None,
62        }
63    }
64}
65
66/// The name of an interface type: `pkg/msg/Name`, `pkg/srv/Name`, or a
67/// part of a service such as `pkg/srv/Name_Request`.
68#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
69pub struct TypeName {
70    /// The package.
71    pub package: String,
72    /// `msg`, `srv` or `action`.
73    pub kind: InterfaceKind,
74    /// The name in the package.
75    pub name: String,
76}
77
78impl TypeName {
79    /// `package/kind/name`, its parts checked.
80    pub fn new(package: &str, kind: InterfaceKind, name: &str) -> Result<TypeName> {
81        validate_package_name(package)?;
82        validate_type_base_name(name)?;
83        Ok(TypeName {
84            package: package.to_string(),
85            kind,
86            name: name.to_string(),
87        })
88    }
89
90    /// A message type `package/msg/name`.
91    pub fn message(package: &str, name: &str) -> Result<TypeName> {
92        TypeName::new(package, InterfaceKind::Message, name)
93    }
94
95    /// Parses `pkg/msg/Name`, `pkg/srv/Name` or `pkg/action/Name`; `pkg/Name`
96    /// is the message `pkg/msg/Name`.
97    pub fn parse(s: &str) -> Result<TypeName> {
98        let parts: Vec<&str> = s.split('/').collect();
99        match parts.as_slice() {
100            [p, n] => TypeName::new(p, InterfaceKind::Message, n),
101            [p, k, n] => match InterfaceKind::parse(k) {
102                Some(kind) => TypeName::new(p, kind, n),
103                None => Err(Error::Name(format!(
104                    "{s:?}: the kind must be msg, srv or action"
105                ))),
106            },
107            _ => Err(Error::Name(format!(
108                "{s:?} is not a type name pkg/msg/Name"
109            ))),
110        }
111    }
112
113    /// The name with a suffix: `pkg/srv/Name` and `_Request` is
114    /// `pkg/srv/Name_Request`.
115    pub fn with_suffix(&self, suffix: &str) -> TypeName {
116        TypeName {
117            package: self.package.clone(),
118            kind: self.kind,
119            name: format!("{}{suffix}", self.name),
120        }
121    }
122
123    /// The DDS type name: `pkg::msg::dds_::Name_`.
124    pub fn dds_name(&self) -> String {
125        format!(
126            "{}::{}::dds_::{}_",
127            self.package,
128            self.kind.as_str(),
129            self.name
130        )
131    }
132
133    /// The type of a DDS type name `pkg::msg::dds_::Name_`, if it is one
134    /// that ROS 2 makes.
135    pub fn from_dds_name(dds: &str) -> Option<TypeName> {
136        let parts: Vec<&str> = dds.split("::").collect();
137        match parts.as_slice() {
138            [p, k, "dds_", n] => {
139                let kind = InterfaceKind::parse(k)?;
140                let n = n.strip_suffix('_')?;
141                TypeName::new(p, kind, n).ok()
142            }
143            _ => None,
144        }
145    }
146}
147
148impl fmt::Display for TypeName {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        write!(f, "{}/{}/{}", self.package, self.kind.as_str(), self.name)
151    }
152}
153
154fn is_name_char(c: char) -> bool {
155    c.is_ascii_alphanumeric() || c == '_'
156}
157
158/// Checks the tokens of a name (between the `/`).
159fn validate_tokens(what: &str, name: &str, body: &str) -> Result<()> {
160    if body.is_empty() {
161        return Ok(());
162    }
163    if body.ends_with('/') {
164        return Err(Error::Name(format!("{what} {name:?} ends with '/'")));
165    }
166    for token in body.split('/') {
167        if token.is_empty() {
168            return Err(Error::Name(format!("{what} {name:?} has an empty token")));
169        }
170        if let Some(c) = token.chars().find(|c| !is_name_char(*c)) {
171            return Err(Error::Name(format!(
172                "{what} {name:?} has the character {c:?}"
173            )));
174        }
175        if token.starts_with(|c: char| c.is_ascii_digit()) {
176            return Err(Error::Name(format!(
177                "{what} {name:?} has a token that starts with a digit"
178            )));
179        }
180    }
181    if name.contains("__") {
182        return Err(Error::Name(format!("{what} {name:?} has '__'")));
183    }
184    Ok(())
185}
186
187/// Checks a fully qualified topic or service name: `/` or `/a/b`.
188pub fn validate_full_topic_name(name: &str) -> Result<()> {
189    let Some(body) = name.strip_prefix('/') else {
190        return Err(Error::Name(format!(
191            "topic name {name:?} is not fully qualified (does not start with '/')"
192        )));
193    };
194    if body.is_empty() {
195        return Err(Error::Name("topic name \"/\" is empty".to_string()));
196    }
197    validate_tokens("topic name", name, body)
198}
199
200/// Checks a node name: `[A-Za-z_][A-Za-z0-9_]*`, without `__`.
201pub fn validate_node_name(name: &str) -> Result<()> {
202    if name.is_empty() {
203        return Err(Error::Name("the node name is empty".to_string()));
204    }
205    if name.contains('/') {
206        return Err(Error::Name(format!("node name {name:?} has '/'")));
207    }
208    validate_tokens("node name", name, name)
209}
210
211/// Checks a namespace: `/` or `/a/b`.
212pub fn validate_namespace(namespace: &str) -> Result<()> {
213    let Some(body) = namespace.strip_prefix('/') else {
214        return Err(Error::Name(format!(
215            "namespace {namespace:?} does not start with '/'"
216        )));
217    };
218    validate_tokens("namespace", namespace, body)
219}
220
221/// Checks a package name: `[a-z][a-z0-9_]*`, without `__` and not
222/// ending with `_`.
223pub fn validate_package_name(name: &str) -> Result<()> {
224    let ok = name.starts_with(|c: char| c.is_ascii_lowercase())
225        && name
226            .chars()
227            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
228        && !name.contains("__")
229        && !name.ends_with('_');
230    if ok {
231        Ok(())
232    } else {
233        Err(Error::Name(format!(
234            "package name {name:?} is not [a-z][a-z0-9_]* (without '__', not ending in '_')"
235        )))
236    }
237}
238
239/// Checks the base name of a type: `[A-Z][A-Za-z0-9_]*`.
240pub fn validate_type_base_name(name: &str) -> Result<()> {
241    let ok = name.starts_with(|c: char| c.is_ascii_uppercase()) && name.chars().all(is_name_char);
242    if ok {
243        Ok(())
244    } else {
245        Err(Error::Name(format!(
246            "type name {name:?} is not [A-Z][A-Za-z0-9_]*"
247        )))
248    }
249}
250
251/// The fully qualified name of node `name` in `namespace`: `/ns/name`.
252pub fn node_full_name(namespace: &str, name: &str) -> String {
253    if namespace == "/" {
254        format!("/{name}")
255    } else {
256        format!("{namespace}/{name}")
257    }
258}
259
260/// Expands a topic or service name for node `node_name` in
261/// `namespace`: a name that starts with `/` is kept, `~` and `~/x` are
262/// the node's own (`/ns/node`, `/ns/node/x`), and the others are in the
263/// namespace (`x` is `/ns/x`). The result is checked.
264pub fn expand_topic_name(name: &str, node_name: &str, namespace: &str) -> Result<String> {
265    validate_namespace(namespace)?;
266    validate_node_name(node_name)?;
267    let full = if name.starts_with('/') {
268        name.to_string()
269    } else if name == "~" {
270        node_full_name(namespace, node_name)
271    } else if let Some(rest) = name.strip_prefix("~/") {
272        format!("{}/{rest}", node_full_name(namespace, node_name))
273    } else if namespace == "/" {
274        format!("/{name}")
275    } else {
276        format!("{namespace}/{name}")
277    };
278    if full.contains('{') || full.contains('~') {
279        return Err(Error::Name(format!(
280            "topic name {name:?}: substitutions are not supported"
281        )));
282    }
283    validate_full_topic_name(&full)?;
284    Ok(full)
285}
286
287/// The DDS topic of a ROS 2 topic: `/chatter` is `rt/chatter`.
288pub fn topic_to_dds(full_name: &str) -> Result<String> {
289    validate_full_topic_name(full_name)?;
290    Ok(format!("{TOPIC_PREFIX}{full_name}"))
291}
292
293/// The DDS topics of the requests and of the replies of a ROS 2
294/// service: `/add_two_ints` is `rq/add_two_intsRequest` and
295/// `rr/add_two_intsReply`.
296pub fn service_to_dds(full_name: &str) -> Result<(String, String)> {
297    validate_full_topic_name(full_name)?;
298    Ok((
299        format!("{REQUEST_PREFIX}{full_name}{REQUEST_SUFFIX}"),
300        format!("{REPLY_PREFIX}{full_name}{REPLY_SUFFIX}"),
301    ))
302}
303
304/// What a DDS topic is in ROS 2.
305#[derive(Clone, Debug, PartialEq, Eq)]
306pub enum DdsTopic {
307    /// The ROS 2 topic of this name (`rt/`).
308    Topic(String),
309    /// The requests of the ROS 2 service of this name (`rq/`).
310    Request(String),
311    /// The replies of the ROS 2 service of this name (`rr/`).
312    Reply(String),
313}
314
315/// The ROS 2 topic or service of a DDS topic, if ROS 2 made it.
316pub fn topic_from_dds(dds: &str) -> Option<DdsTopic> {
317    let ros = |prefix: &str, suffix: &str| -> Option<String> {
318        let rest = dds.strip_prefix(prefix)?.strip_suffix(suffix)?;
319        rest.starts_with('/')
320            .then(|| rest.to_string())
321            .filter(|n| validate_full_topic_name(n).is_ok())
322    };
323    if let Some(n) = ros(TOPIC_PREFIX, "") {
324        Some(DdsTopic::Topic(n))
325    } else if let Some(n) = ros(REQUEST_PREFIX, REQUEST_SUFFIX) {
326        Some(DdsTopic::Request(n))
327    } else {
328        ros(REPLY_PREFIX, REPLY_SUFFIX).map(DdsTopic::Reply)
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn type_names() {
338        let t = TypeName::parse("std_msgs/msg/String").unwrap();
339        assert_eq!(t.dds_name(), "std_msgs::msg::dds_::String_");
340        assert_eq!(t.to_string(), "std_msgs/msg/String");
341        assert_eq!(TypeName::parse("std_msgs/String").unwrap(), t);
342        assert_eq!(
343            TypeName::from_dds_name("std_msgs::msg::dds_::String_"),
344            Some(t)
345        );
346        let s = TypeName::parse("example_interfaces/srv/AddTwoInts").unwrap();
347        assert_eq!(
348            s.with_suffix("_Request").dds_name(),
349            "example_interfaces::srv::dds_::AddTwoInts_Request_"
350        );
351        assert!(TypeName::parse("Std/msg/String").is_err());
352        assert!(TypeName::parse("std_msgs/msg/string").is_err());
353        assert!(TypeName::parse("std_msgs/foo/String").is_err());
354        assert_eq!(TypeName::from_dds_name("HelloWorld"), None);
355    }
356
357    #[test]
358    fn topics() {
359        assert_eq!(topic_to_dds("/chatter").unwrap(), "rt/chatter");
360        assert_eq!(
361            service_to_dds("/add_two_ints").unwrap(),
362            (
363                "rq/add_two_intsRequest".to_string(),
364                "rr/add_two_intsReply".to_string()
365            )
366        );
367        assert!(topic_to_dds("chatter").is_err());
368        assert!(topic_to_dds("/a//b").is_err());
369        assert!(topic_to_dds("/a/").is_err());
370        assert!(topic_to_dds("/a/1b").is_err());
371        assert!(topic_to_dds("/a__b").is_err());
372        assert!(topic_to_dds("/a-b").is_err());
373        assert_eq!(
374            topic_from_dds("rt/ns/chatter"),
375            Some(DdsTopic::Topic("/ns/chatter".into()))
376        );
377        assert_eq!(
378            topic_from_dds("rq/add_two_intsRequest"),
379            Some(DdsTopic::Request("/add_two_ints".into()))
380        );
381        assert_eq!(
382            topic_from_dds("rr/add_two_intsReply"),
383            Some(DdsTopic::Reply("/add_two_ints".into()))
384        );
385        assert_eq!(topic_from_dds("ros_discovery_info"), None);
386    }
387
388    #[test]
389    fn expansion() {
390        assert_eq!(
391            expand_topic_name("chatter", "talker", "/").unwrap(),
392            "/chatter"
393        );
394        assert_eq!(
395            expand_topic_name("chatter", "talker", "/robot").unwrap(),
396            "/robot/chatter"
397        );
398        assert_eq!(expand_topic_name("/x", "talker", "/robot").unwrap(), "/x");
399        assert_eq!(
400            expand_topic_name("~/state", "talker", "/robot").unwrap(),
401            "/robot/talker/state"
402        );
403        assert_eq!(expand_topic_name("~", "talker", "/").unwrap(), "/talker");
404        assert!(expand_topic_name("{node}/x", "talker", "/").is_err());
405        assert!(expand_topic_name("x", "1talker", "/").is_err());
406        assert!(expand_topic_name("x", "talker", "robot").is_err());
407        assert!(validate_namespace("/").is_ok());
408        assert!(validate_namespace("/a/b").is_ok());
409        assert!(validate_namespace("/a/").is_err());
410    }
411}