Skip to main content

microrti_client/
handles.rs

1//! Opaque handles (12.2, 12.13.3.3 c).
2//!
3//! A handle is the byte string an RTI produced for a designator. This crate stores and compares the bytes
4//! and never looks inside, so it works with the handle encoding of any HLA 4 RTI.
5
6use std::fmt;
7
8use bytes::Bytes;
9use microrti_core::{ExceptionKind, RtiError, RtiResult};
10use microrti_proto as proto;
11
12use crate::wire::{FromWire, ToWire, WireCx, malformed};
13
14fn write_hex(bytes: &[u8], f: &mut fmt::Formatter<'_>) -> fmt::Result {
15    for byte in bytes {
16        write!(f, "{byte:02x}")?;
17    }
18    Ok(())
19}
20
21macro_rules! handles {
22    ($($(#[$doc:meta])* $name:ident;)+) => {$(
23        $(#[$doc])*
24        ///
25        /// Opaque: equality, ordering and hashing work on the encoded bytes. `Display` prints them in
26        /// hexadecimal.
27        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
28        pub struct $name(Bytes);
29
30        impl $name {
31            /// Wraps the encoded form of a handle exactly as an RTI produced it.
32            pub fn from_encoded(encoded: impl Into<Bytes>) -> Self {
33                Self(encoded.into())
34            }
35
36            /// Reconstitutes a handle that was received as a value, for example inside an attribute or
37            /// parameter value (12.2). Fails with `CouldNotDecode` when there are no bytes at all.
38            pub fn decode(encoded: &[u8]) -> RtiResult<Self> {
39                if encoded.is_empty() {
40                    return Err(RtiError::new(
41                        ExceptionKind::CouldNotDecode,
42                        concat!("an encoded ", stringify!($name), " cannot be empty"),
43                    ));
44                }
45                Ok(Self(Bytes::copy_from_slice(encoded)))
46            }
47
48            /// The encoded form, ready to be sent as a value to other federates (12.2).
49            pub fn encode(&self) -> Bytes {
50                self.0.clone()
51            }
52
53            /// The encoded bytes.
54            pub fn as_bytes(&self) -> &[u8] {
55                &self.0
56            }
57
58            /// Number of bytes of the encoded form.
59            pub fn encoded_length(&self) -> usize {
60                self.0.len()
61            }
62        }
63
64        impl AsRef<[u8]> for $name {
65            fn as_ref(&self) -> &[u8] {
66                &self.0
67            }
68        }
69
70        impl fmt::Display for $name {
71            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72                write_hex(&self.0, f)
73            }
74        }
75
76        impl fmt::Debug for $name {
77            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78                f.write_str(concat!(stringify!($name), "("))?;
79                write_hex(&self.0, f)?;
80                f.write_str(")")
81            }
82        }
83
84        impl ToWire<Option<proto::$name>> for &$name {
85            fn to_wire(self, _: &WireCx) -> RtiResult<Option<proto::$name>> {
86                Ok(Some(proto::$name { data: self.0.clone() }))
87            }
88        }
89
90        impl FromWire<Option<proto::$name>> for $name {
91            fn from_wire(wire: Option<proto::$name>, _: &WireCx) -> RtiResult<Self> {
92                match wire {
93                    Some(handle) => Ok(Self(handle.data)),
94                    None => Err(malformed(concat!("missing ", stringify!($name)))),
95                }
96            }
97        }
98
99        /// An absent (or empty) handle is "no value" (12.10).
100        impl FromWire<Option<proto::$name>> for Option<$name> {
101            fn from_wire(wire: Option<proto::$name>, _: &WireCx) -> RtiResult<Self> {
102                Ok(wire.filter(|handle| !handle.data.is_empty()).map(|handle| $name(handle.data)))
103            }
104        }
105    )+};
106}
107
108handles! {
109    /// Handle of a joined federate.
110    FederateHandle;
111    /// Handle of an object class of the FDD.
112    ObjectClassHandle;
113    /// Handle of a class attribute of the FDD.
114    AttributeHandle;
115    /// Handle of an interaction class of the FDD.
116    InteractionClassHandle;
117    /// Handle of an interaction parameter of the FDD.
118    ParameterHandle;
119    /// Handle of an object instance.
120    ObjectInstanceHandle;
121    /// Handle of a dimension of the FDD.
122    DimensionHandle;
123    /// Handle of a region created with Create Region.
124    RegionHandle;
125    /// Handle of a transportation type.
126    TransportationTypeHandle;
127    /// Handle of a sent message that may still be retracted.
128    MessageRetractionHandle;
129}