Skip to main content

How Type Safety Works

TopicManager enforces type safety internally using Rust’s TypeId mechanism. While the API no longer exposes generic type parameters, type consistency is still validated to prevent mismatched message types. Type safety is enforced at two levels:
  1. Compile-time type checking: When using send_message<T>, the compiler ensures you’re sending a type that implements SerializableMessage. The type information is extracted from the type name and tracked internally.
  2. Runtime validation: TopicManager uses TypeId internally to ensure that all publishers and subscribers for a given topic use compatible message types. Type mismatches are detected during deserialization.

Example: Type-Safe Messaging

#[derive(Copy, Clone, Debug)]
#[repr(C)]
struct SensorData {
    temperature: f32,
    timestamp: u64,
}

// send_message enforces type at compile time
let data = SensorData {
    temperature: 23.5,
    timestamp: 1234567890,
};
manager.send_message("sensors/temperature", &data)?;

// When receiving, deserialization validates the type
match manager.pull("sensors/temperature") {
    Ok(Some(bytes)) => {
        // from_bytes() will fail if the message type doesn't match
        match SensorData::from_bytes(&bytes) {
            Ok(reading) => println!("Received: {}°C", reading.temperature),
            Err(e) => eprintln!("Type mismatch: {}", e),
        }
    }
    Ok(None) => {}
    Err(e) => eprintln!("Error: {}", e),
}

Schema-Based Type Validation

For ROS2 message types, TopicManager can also validate schemas using the schema registry. When a schema is available for a message type, it’s used to ensure compatibility across different publishers and subscribers.
Type mismatches are caught at runtime during deserialization. If you send a message of type A but try to deserialize it as type B, the from_bytes() call will return an error. This prevents silent data corruption.
Type safety prevents common errors like sending the wrong message type or mismatched field layouts. This is especially important for cross-language communication and when working with ROS2 message types.

Next Steps