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 {
pub fn from_encoded(encoded: impl Into<Bytes>) -> Self {
Self(encoded.into())
}
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)))
}
pub fn encode(&self) -> Bytes {
self.0.clone()
}
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
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)))),
}
}
}
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! {
FederateHandle;
ObjectClassHandle;
AttributeHandle;
InteractionClassHandle;
ParameterHandle;
ObjectInstanceHandle;
DimensionHandle;
RegionHandle;
TransportationTypeHandle;
MessageRetractionHandle;
}