microrti-client 0.1.2

Federate side of HLA 4 (IEEE 1516.1-2025): RtiAmbassador and FederateAmbassador over an abstract RTI link.
Documentation
//! Opaque handles (12.2, 12.13.3.3 c).
//!
//! A handle is the byte string an RTI produced for a designator. This crate stores and compares the bytes
//! and never looks inside, so it works with the handle encoding of any HLA 4 RTI.

use std::fmt;

use bytes::Bytes;
use microrti_core::{ExceptionKind, RtiError, RtiResult};
use microrti_proto as proto;

use crate::wire::{FromWire, ToWire, WireCx, malformed};

fn write_hex(bytes: &[u8], f: &mut fmt::Formatter<'_>) -> fmt::Result {
    for byte in bytes {
        write!(f, "{byte:02x}")?;
    }
    Ok(())
}

macro_rules! handles {
    ($($(#[$doc:meta])* $name:ident;)+) => {$(
        $(#[$doc])*
        ///
        /// Opaque: equality, ordering and hashing work on the encoded bytes. `Display` prints them in
        /// hexadecimal.
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $name(Bytes);

        impl $name {
            /// Wraps the encoded form of a handle exactly as an RTI produced it.
            pub fn from_encoded(encoded: impl Into<Bytes>) -> Self {
                Self(encoded.into())
            }

            /// Reconstitutes a handle that was received as a value, for example inside an attribute or
            /// parameter value (12.2). Fails with `CouldNotDecode` when there are no bytes at all.
            pub fn decode(encoded: &[u8]) -> RtiResult<Self> {
                if encoded.is_empty() {
                    return Err(RtiError::new(
                        ExceptionKind::CouldNotDecode,
                        concat!("an encoded ", stringify!($name), " cannot be empty"),
                    ));
                }
                Ok(Self(Bytes::copy_from_slice(encoded)))
            }

            /// The encoded form, ready to be sent as a value to other federates (12.2).
            pub fn encode(&self) -> Bytes {
                self.0.clone()
            }

            /// The encoded bytes.
            pub fn as_bytes(&self) -> &[u8] {
                &self.0
            }

            /// Number of bytes of the encoded form.
            pub fn encoded_length(&self) -> usize {
                self.0.len()
            }
        }

        impl AsRef<[u8]> for $name {
            fn as_ref(&self) -> &[u8] {
                &self.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write_hex(&self.0, f)
            }
        }

        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(concat!(stringify!($name), "("))?;
                write_hex(&self.0, f)?;
                f.write_str(")")
            }
        }

        impl ToWire<Option<proto::$name>> for &$name {
            fn to_wire(self, _: &WireCx) -> RtiResult<Option<proto::$name>> {
                Ok(Some(proto::$name { data: self.0.clone() }))
            }
        }

        impl FromWire<Option<proto::$name>> for $name {
            fn from_wire(wire: Option<proto::$name>, _: &WireCx) -> RtiResult<Self> {
                match wire {
                    Some(handle) => Ok(Self(handle.data)),
                    None => Err(malformed(concat!("missing ", stringify!($name)))),
                }
            }
        }

        /// An absent (or empty) handle is "no value" (12.10).
        impl FromWire<Option<proto::$name>> for Option<$name> {
            fn from_wire(wire: Option<proto::$name>, _: &WireCx) -> RtiResult<Self> {
                Ok(wire.filter(|handle| !handle.data.is_empty()).map(|handle| $name(handle.data)))
            }
        }
    )+};
}

handles! {
    /// Handle of a joined federate.
    FederateHandle;
    /// Handle of an object class of the FDD.
    ObjectClassHandle;
    /// Handle of a class attribute of the FDD.
    AttributeHandle;
    /// Handle of an interaction class of the FDD.
    InteractionClassHandle;
    /// Handle of an interaction parameter of the FDD.
    ParameterHandle;
    /// Handle of an object instance.
    ObjectInstanceHandle;
    /// Handle of a dimension of the FDD.
    DimensionHandle;
    /// Handle of a region created with Create Region.
    RegionHandle;
    /// Handle of a transportation type.
    TransportationTypeHandle;
    /// Handle of a sent message that may still be retracted.
    MessageRetractionHandle;
}