Skip to main content

rustorb_dds_ros2/
user_data.rs

1//! The USER_DATA of ROS 2 participants, writers and readers: entries
2//! `key=value;`, one after the other.
3//!
4//! ROS 2 (Jazzy) announces `enclave=/;` for a participant and
5//! `typehash=RIHS01_...;` for a writer or a reader. Other programs may
6//! add their own entries; [`UserData`] keeps them in order.
7
8use crate::type_description::TypeHash;
9
10/// The key of the type hash of a writer or reader.
11pub const TYPE_HASH_KEY: &str = "typehash";
12/// The key of the security enclave of a participant.
13pub const ENCLAVE_KEY: &str = "enclave";
14
15/// Entries `key=value;`.
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
17pub struct UserData {
18    entries: Vec<(String, String)>,
19}
20
21impl UserData {
22    /// No entries.
23    pub fn new() -> UserData {
24        UserData::default()
25    }
26
27    /// The entries of USER_DATA octets. Octets that are not entries
28    /// (not UTF-8, or a part without `=`) are left out.
29    pub fn parse(octets: &[u8]) -> UserData {
30        let Ok(s) = std::str::from_utf8(octets) else {
31            return UserData::new();
32        };
33        let entries = s
34            .split(';')
35            .filter_map(|e| {
36                let (k, v) = e.split_once('=')?;
37                let k = k.trim();
38                (!k.is_empty()).then(|| (k.to_string(), v.trim().to_string()))
39            })
40            .collect();
41        UserData { entries }
42    }
43
44    /// The entries, in order.
45    pub fn entries(&self) -> &[(String, String)] {
46        &self.entries
47    }
48
49    /// The value of `key`.
50    pub fn get(&self, key: &str) -> Option<&str> {
51        self.entries
52            .iter()
53            .find(|(k, _)| k == key)
54            .map(|(_, v)| v.as_str())
55    }
56
57    /// Sets `key` to `value`, in place if it is there, else at the end.
58    /// `key` must not have `=` or `;`, `value` not `;`.
59    pub fn set(&mut self, key: &str, value: &str) -> &mut Self {
60        debug_assert!(!key.contains(['=', ';']) && !value.contains(';'));
61        match self.entries.iter_mut().find(|(k, _)| k == key) {
62            Some(e) => e.1 = value.to_string(),
63            None => self.entries.push((key.to_string(), value.to_string())),
64        }
65        self
66    }
67
68    /// Takes the entries of `other` (theirs win).
69    pub fn merge(&mut self, other: &UserData) -> &mut Self {
70        for (k, v) in &other.entries {
71            self.set(k, v);
72        }
73        self
74    }
75
76    /// The type hash, if there is a valid one.
77    pub fn type_hash(&self) -> Option<TypeHash> {
78        TypeHash::parse(self.get(TYPE_HASH_KEY)?)
79    }
80
81    /// Sets the type hash.
82    pub fn set_type_hash(&mut self, hash: &TypeHash) -> &mut Self {
83        self.set(TYPE_HASH_KEY, &hash.to_string())
84    }
85
86    /// The octets: each entry `key=value;`.
87    pub fn to_bytes(&self) -> Vec<u8> {
88        self.entries
89            .iter()
90            .map(|(k, v)| format!("{k}={v};"))
91            .collect::<String>()
92            .into_bytes()
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn round_trip() {
102        let h = "RIHS01_df668c740482bbd48fb39d76a70dfd4bd59db1288021743503259e948f6b1a18";
103        let mut u = UserData::parse(format!("typehash={h};").as_bytes());
104        assert_eq!(u.type_hash().unwrap().to_string(), h);
105        u.set("juiz", "1234");
106        assert_eq!(
107            u.to_bytes(),
108            format!("typehash={h};juiz=1234;").into_bytes()
109        );
110        let v = UserData::parse(&u.to_bytes());
111        assert_eq!(v, u);
112        assert_eq!(v.get("juiz"), Some("1234"));
113        assert_eq!(UserData::parse(b"enclave=/;").get(ENCLAVE_KEY), Some("/"));
114        assert_eq!(UserData::parse(&[0xff, 0xfe]).entries().len(), 0);
115        assert_eq!(UserData::parse(b"clientid= 1.2.3;x").entries().len(), 1);
116    }
117}