microrti_client/
handles.rs1use 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 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
28 pub struct $name(Bytes);
29
30 impl $name {
31 pub fn from_encoded(encoded: impl Into<Bytes>) -> Self {
33 Self(encoded.into())
34 }
35
36 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 pub fn encode(&self) -> Bytes {
50 self.0.clone()
51 }
52
53 pub fn as_bytes(&self) -> &[u8] {
55 &self.0
56 }
57
58 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 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 FederateHandle;
111 ObjectClassHandle;
113 AttributeHandle;
115 InteractionClassHandle;
117 ParameterHandle;
119 ObjectInstanceHandle;
121 DimensionHandle;
123 RegionHandle;
125 TransportationTypeHandle;
127 MessageRetractionHandle;
129}