use std::fmt::Write as _;
use sha2::{Digest, Sha256};
#[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;
pub const ARRAY_OFFSET: u8 = 48;
pub const BOUNDED_SEQUENCE_OFFSET: u8 = 96;
pub const UNBOUNDED_SEQUENCE_OFFSET: u8 = 144;
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FieldType {
pub type_id: u8,
pub capacity: u64,
pub string_capacity: u64,
pub nested_type_name: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Field {
pub name: String,
pub field_type: FieldType,
pub default_value: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct IndividualTypeDescription {
pub type_name: String,
pub fields: Vec<Field>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TypeDescription {
pub type_description: IndividualTypeDescription,
pub referenced_type_descriptions: Vec<IndividualTypeDescription>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TypeHash {
pub version: u8,
pub value: [u8; 32],
}
impl TypeHash {
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 })
}
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(())
}
}
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 {
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
}
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()
}
#[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\"");
}
}