microrti-client 0.2.0

Federate side of HLA 4 (IEEE 1516.1-2025): RtiAmbassador and FederateAmbassador over an abstract RTI link.
Documentation
//! Hand-written companions of the generated [`Callback`] enum and [`FederateAmbassador`] trait.

use crate::callback::{Callback, FederateAmbassador};
use crate::types::{SupplementalReceiveInfo, SupplementalReflectInfo};

/// The one exception a federate ambassador may raise: something went wrong inside the federate while it
/// handled a callback.
///
/// The RTI ambassador reports it to the RTI as a failed callback response carrying the standard exception
/// name `FederateInternalError` and this message.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("FederateInternalError: {message}")]
pub struct FederateInternalError {
    /// Free-form details for humans.
    pub message: String,
}

impl FederateInternalError {
    /// Standard name of the exception.
    pub const NAME: &'static str = "FederateInternalError";

    /// Creates the error.
    pub fn new(message: impl Into<String>) -> Self {
        Self { message: message.into() }
    }
}

impl From<String> for FederateInternalError {
    fn from(message: String) -> Self {
        Self { message }
    }
}

impl From<&str> for FederateInternalError {
    fn from(message: &str) -> Self {
        Self::new(message)
    }
}

/// Result of every [`FederateAmbassador`] method.
pub type CallbackResult = Result<(), FederateInternalError>;

/// A federate ambassador that ignores every callback (the `NullFederateAmbassador` of the standard APIs).
#[derive(Clone, Copy, Debug, Default)]
pub struct NullFederateAmbassador;

impl FederateAmbassador for NullFederateAmbassador {}

/// Adapts a closure taking the [`Callback`] enum into a [`FederateAmbassador`], for federates that prefer
/// one `match` over implementing trait methods.
///
/// ```
/// use microrti_client::{Callback, CallbackFn};
///
/// let mut discovered = Vec::new();
/// let _federate = CallbackFn::new(move |callback: Callback| {
///     if let Callback::DiscoverObjectInstance { object_instance_name, .. } = callback {
///         discovered.push(object_instance_name);
///     }
///     Ok(())
/// });
/// ```
pub struct CallbackFn<F>(F);

impl<F> CallbackFn<F>
where
    F: FnMut(Callback) -> CallbackResult,
{
    /// Wraps the closure.
    pub fn new(handler: F) -> Self {
        Self(handler)
    }
}

impl<F> FederateAmbassador for CallbackFn<F>
where
    F: FnMut(Callback) -> CallbackResult,
{
    fn handle_callback(&mut self, callback: Callback) -> CallbackResult {
        (self.0)(callback)
    }
}

impl<F> std::fmt::Debug for CallbackFn<F> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("CallbackFn")
    }
}

impl Callback {
    /// For the two Reflect Attribute Values callbacks (6.11): the producing federate and the conveyed
    /// regions as one value. `None` for every other callback.
    pub fn supplemental_reflect_info(&self) -> Option<SupplementalReflectInfo> {
        match self {
            Callback::ReflectAttributeValues { producing_federate, sent_regions, .. }
            | Callback::ReflectAttributeValuesWithTime { producing_federate, sent_regions, .. } => {
                Some(SupplementalReflectInfo {
                    producing_federate: producing_federate.clone(),
                    sent_regions: sent_regions.clone(),
                })
            }
            _ => None,
        }
    }

    /// For the Receive Interaction and Receive Directed Interaction callbacks (6.13, 6.15): the producing
    /// federate and the conveyed regions as one value (directed interactions never convey regions). `None`
    /// for every other callback.
    pub fn supplemental_receive_info(&self) -> Option<SupplementalReceiveInfo> {
        match self {
            Callback::ReceiveInteraction { producing_federate, sent_regions, .. }
            | Callback::ReceiveInteractionWithTime { producing_federate, sent_regions, .. } => {
                Some(SupplementalReceiveInfo {
                    producing_federate: producing_federate.clone(),
                    sent_regions: sent_regions.clone(),
                })
            }
            Callback::ReceiveDirectedInteraction { producing_federate, .. }
            | Callback::ReceiveDirectedInteractionWithTime { producing_federate, .. } => {
                Some(SupplementalReceiveInfo {
                    producing_federate: producing_federate.clone(),
                    sent_regions: None,
                })
            }
            _ => None,
        }
    }
}