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 description of a type that ROS 2 hashes (REP-2011, "Evolving
//! Message Types"), and its hash `RIHS01_<sha256>`.
//!
//! The description is the message `type_description_interfaces/msg/TypeDescription`:
//! the type, and the types it uses (directly or not) sorted by name, each
//! a name and its fields. A field is a name and a type: a type ID, the
//! capacity of an array or a bounded sequence, the bound of a bounded
//! string, and the name of a nested type.
//!
//! The RIHS01 hash (REP-2011) is the SHA-256 of the description written
//! in JSON without the fields' default values, the members in the order
//! of the messages, `", "` and `": "` between them, all on one line and
//! non-ASCII characters escaped. That is the hash ROS 2 Jazzy announces:
//! the hashes of `std_msgs/msg/String` and of the request and response of
//! `example_interfaces/srv/AddTwoInts` are tested below, and
//! interop/ros2.sh compares those of every interface of an installation
//! with the ones it ships.

use std::fmt::Write as _;

use sha2::{Digest, Sha256};

/// The type IDs of `type_description_interfaces/msg/FieldType`.
#[allow(missing_docs)]
pub mod field_type {
    pub const NOT_SET: u8 = 0;
    pub const NESTED_TYPE: u8 = 1;
    pub const INT8: u8 = 2;
    pub const UINT8: u8 = 3;
    pub const INT16: u8 = 4;
    pub const UINT16: u8 = 5;
    pub const INT32: u8 = 6;
    pub const UINT32: u8 = 7;
    pub const INT64: u8 = 8;
    pub const UINT64: u8 = 9;
    pub const FLOAT: u8 = 10;
    pub const DOUBLE: u8 = 11;
    pub const LONG_DOUBLE: u8 = 12;
    pub const CHAR: u8 = 13;
    pub const WCHAR: u8 = 14;
    pub const BOOLEAN: u8 = 15;
    pub const BYTE: u8 = 16;
    pub const STRING: u8 = 17;
    pub const WSTRING: u8 = 18;
    pub const FIXED_STRING: u8 = 19;
    pub const FIXED_WSTRING: u8 = 20;
    pub const BOUNDED_STRING: u8 = 21;
    pub const BOUNDED_WSTRING: u8 = 22;
    /// Added to the ID of the element of an array (`T[N]`).
    pub const ARRAY_OFFSET: u8 = 48;
    /// Added to the ID of the element of a bounded sequence (`T[<=N]`).
    pub const BOUNDED_SEQUENCE_OFFSET: u8 = 96;
    /// Added to the ID of the element of a sequence (`T[]`).
    pub const UNBOUNDED_SEQUENCE_OFFSET: u8 = 144;
}

/// `type_description_interfaces/msg/FieldType`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FieldType {
    /// The type ID ([`field_type`]).
    pub type_id: u8,
    /// The length of an array or the bound of a bounded sequence; 0
    /// otherwise.
    pub capacity: u64,
    /// The bound of a bounded string; 0 otherwise.
    pub string_capacity: u64,
    /// The name of a nested type (`pkg/msg/Name`); empty otherwise.
    pub nested_type_name: String,
}

/// `type_description_interfaces/msg/Field`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Field {
    /// The name.
    pub name: String,
    /// The type.
    pub field_type: FieldType,
    /// The default value as written; not hashed.
    pub default_value: String,
}

/// `type_description_interfaces/msg/IndividualTypeDescription`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct IndividualTypeDescription {
    /// `pkg/msg/Name`.
    pub type_name: String,
    /// The fields, in order.
    pub fields: Vec<Field>,
}

/// `type_description_interfaces/msg/TypeDescription`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TypeDescription {
    /// The type.
    pub type_description: IndividualTypeDescription,
    /// The types it uses, directly or not, sorted by name.
    pub referenced_type_descriptions: Vec<IndividualTypeDescription>,
}

/// A type hash: `RIHS01_` and the SHA-256, in hexadecimal.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TypeHash {
    /// The version: 1.
    pub version: u8,
    /// The SHA-256.
    pub value: [u8; 32],
}

impl TypeHash {
    /// Parses `RIHS01_<64 hexadecimal digits>`.
    pub fn parse(s: &str) -> Option<TypeHash> {
        let hex = s.strip_prefix("RIHS01_")?;
        if hex.len() != 64 {
            return None;
        }
        let mut value = [0u8; 32];
        for (i, v) in value.iter_mut().enumerate() {
            *v = u8::from_str_radix(hex.get(2 * i..2 * i + 2)?, 16).ok()?;
        }
        Some(TypeHash { version: 1, value })
    }

    /// The `typehash=RIHS01_...;` of the USER_DATA of a ROS 2 writer or
    /// reader.
    pub fn user_data_entry(&self) -> String {
        format!("typehash={self};")
    }
}

impl std::fmt::Display for TypeHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "RIHS{:02}_", self.version)?;
        for b in self.value {
            write!(f, "{b:02x}")?;
        }
        Ok(())
    }
}

/// A JSON string as Python's `json.dumps` writes it by default
/// (`ensure_ascii`).
fn json_string(out: &mut String, s: &str) {
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{8}' => out.push_str("\\b"),
            '\u{c}' => out.push_str("\\f"),
            c if (c as u32) < 0x20 || (c as u32) > 0x7e => {
                let mut buf = [0u16; 2];
                for u in c.encode_utf16(&mut buf) {
                    let _ = write!(out, "\\u{u:04x}");
                }
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

fn json_individual(out: &mut String, d: &IndividualTypeDescription) {
    out.push_str("{\"type_name\": ");
    json_string(out, &d.type_name);
    out.push_str(", \"fields\": [");
    for (i, f) in d.fields.iter().enumerate() {
        if i > 0 {
            out.push_str(", ");
        }
        out.push_str("{\"name\": ");
        json_string(out, &f.name);
        let t = &f.field_type;
        let _ = write!(
            out,
            ", \"type\": {{\"type_id\": {}, \"capacity\": {}, \"string_capacity\": {}, \"nested_type_name\": ",
            t.type_id, t.capacity, t.string_capacity
        );
        json_string(out, &t.nested_type_name);
        out.push_str("}}");
    }
    out.push_str("]}");
}

impl TypeDescription {
    /// The JSON that RIHS01 hashes.
    pub fn hashable_json(&self) -> String {
        let mut out = String::from("{\"type_description\": ");
        json_individual(&mut out, &self.type_description);
        out.push_str(", \"referenced_type_descriptions\": [");
        for (i, d) in self.referenced_type_descriptions.iter().enumerate() {
            if i > 0 {
                out.push_str(", ");
            }
            json_individual(&mut out, d);
        }
        out.push_str("]}");
        out
    }

    /// The RIHS01 hash.
    pub fn hash(&self) -> TypeHash {
        let value: [u8; 32] = Sha256::digest(self.hashable_json().as_bytes()).into();
        TypeHash { version: 1, value }
    }
}

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

    fn field(name: &str, type_id: u8) -> Field {
        Field {
            name: name.into(),
            field_type: FieldType {
                type_id,
                capacity: 0,
                string_capacity: 0,
                nested_type_name: String::new(),
            },
            default_value: String::new(),
        }
    }

    fn hash(name: &str, fields: Vec<Field>) -> String {
        TypeDescription {
            type_description: IndividualTypeDescription {
                type_name: name.into(),
                fields,
            },
            referenced_type_descriptions: Vec::new(),
        }
        .hash()
        .to_string()
    }

    /// The hashes ROS 2 Jazzy announces (`ros2 topic info -v`, and the
    /// USER_DATA of its endpoints in captures).
    #[test]
    fn known_hashes() {
        assert_eq!(
            hash(
                "std_msgs/msg/String",
                vec![field("data", field_type::STRING)]
            ),
            "RIHS01_df668c740482bbd48fb39d76a70dfd4bd59db1288021743503259e948f6b1a18"
        );
        assert_eq!(
            hash(
                "example_interfaces/srv/AddTwoInts_Request",
                vec![field("a", field_type::INT64), field("b", field_type::INT64)]
            ),
            "RIHS01_000c5fd92d6b2e1a05949348f584d6d652adea1e92d691792011ac2273508302"
        );
        assert_eq!(
            hash(
                "example_interfaces/srv/AddTwoInts_Response",
                vec![field("sum", field_type::INT64)]
            ),
            "RIHS01_de5c030d4af33cba2749310b249737b631594703f9300495f48bffb2b44dcc2f"
        );
    }

    #[test]
    fn default_values_are_not_hashed() {
        let mut f = field("data", field_type::STRING);
        f.default_value = "\"x\"".into();
        assert_eq!(
            hash("std_msgs/msg/String", vec![f]),
            "RIHS01_df668c740482bbd48fb39d76a70dfd4bd59db1288021743503259e948f6b1a18"
        );
    }

    #[test]
    fn parse_and_print() {
        let s = "RIHS01_df668c740482bbd48fb39d76a70dfd4bd59db1288021743503259e948f6b1a18";
        let h = TypeHash::parse(s).unwrap();
        assert_eq!(h.to_string(), s);
        assert_eq!(h.user_data_entry(), format!("typehash={s};"));
        assert_eq!(TypeHash::parse("RIHS01_00"), None);
        assert_eq!(
            TypeHash::parse(
                "RIHS02_df668c740482bbd48fb39d76a70dfd4bd59db1288021743503259e948f6b1a18"
            ),
            None
        );
    }

    #[test]
    fn json_escapes() {
        let mut s = String::new();
        json_string(&mut s, "a\"b\\c\né");
        assert_eq!(s, "\"a\\\"b\\\\c\\n\\u00e9\"");
    }
}