rustorb-dds-ros2 0.4.0

The ROS 2 conventions on DDS for rustorb-dds: names, interface types from .msg/.srv, RIHS01 type hashes, node discovery
Documentation
//! The USER_DATA of ROS 2 participants, writers and readers: entries
//! `key=value;`, one after the other.
//!
//! ROS 2 (Jazzy) announces `enclave=/;` for a participant and
//! `typehash=RIHS01_...;` for a writer or a reader. Other programs may
//! add their own entries; [`UserData`] keeps them in order.

use crate::type_description::TypeHash;

/// The key of the type hash of a writer or reader.
pub const TYPE_HASH_KEY: &str = "typehash";
/// The key of the security enclave of a participant.
pub const ENCLAVE_KEY: &str = "enclave";

/// Entries `key=value;`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct UserData {
    entries: Vec<(String, String)>,
}

impl UserData {
    /// No entries.
    pub fn new() -> UserData {
        UserData::default()
    }

    /// The entries of USER_DATA octets. Octets that are not entries
    /// (not UTF-8, or a part without `=`) are left out.
    pub fn parse(octets: &[u8]) -> UserData {
        let Ok(s) = std::str::from_utf8(octets) else {
            return UserData::new();
        };
        let entries = s
            .split(';')
            .filter_map(|e| {
                let (k, v) = e.split_once('=')?;
                let k = k.trim();
                (!k.is_empty()).then(|| (k.to_string(), v.trim().to_string()))
            })
            .collect();
        UserData { entries }
    }

    /// The entries, in order.
    pub fn entries(&self) -> &[(String, String)] {
        &self.entries
    }

    /// The value of `key`.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.entries
            .iter()
            .find(|(k, _)| k == key)
            .map(|(_, v)| v.as_str())
    }

    /// Sets `key` to `value`, in place if it is there, else at the end.
    /// `key` must not have `=` or `;`, `value` not `;`.
    pub fn set(&mut self, key: &str, value: &str) -> &mut Self {
        debug_assert!(!key.contains(['=', ';']) && !value.contains(';'));
        match self.entries.iter_mut().find(|(k, _)| k == key) {
            Some(e) => e.1 = value.to_string(),
            None => self.entries.push((key.to_string(), value.to_string())),
        }
        self
    }

    /// Takes the entries of `other` (theirs win).
    pub fn merge(&mut self, other: &UserData) -> &mut Self {
        for (k, v) in &other.entries {
            self.set(k, v);
        }
        self
    }

    /// The type hash, if there is a valid one.
    pub fn type_hash(&self) -> Option<TypeHash> {
        TypeHash::parse(self.get(TYPE_HASH_KEY)?)
    }

    /// Sets the type hash.
    pub fn set_type_hash(&mut self, hash: &TypeHash) -> &mut Self {
        self.set(TYPE_HASH_KEY, &hash.to_string())
    }

    /// The octets: each entry `key=value;`.
    pub fn to_bytes(&self) -> Vec<u8> {
        self.entries
            .iter()
            .map(|(k, v)| format!("{k}={v};"))
            .collect::<String>()
            .into_bytes()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn round_trip() {
        let h = "RIHS01_df668c740482bbd48fb39d76a70dfd4bd59db1288021743503259e948f6b1a18";
        let mut u = UserData::parse(format!("typehash={h};").as_bytes());
        assert_eq!(u.type_hash().unwrap().to_string(), h);
        u.set("juiz", "1234");
        assert_eq!(
            u.to_bytes(),
            format!("typehash={h};juiz=1234;").into_bytes()
        );
        let v = UserData::parse(&u.to_bytes());
        assert_eq!(v, u);
        assert_eq!(v.get("juiz"), Some("1234"));
        assert_eq!(UserData::parse(b"enclave=/;").get(ENCLAVE_KEY), Some("/"));
        assert_eq!(UserData::parse(&[0xff, 0xfe]).entries().len(), 0);
        assert_eq!(UserData::parse(b"clientid= 1.2.3;x").entries().len(), 1);
    }
}