ara-com 0.1.0

Core traits and async abstractions for Adaptive AUTOSAR communication in Rust
Documentation
use crate::types::*;

/// Marker trait for a service definition. Generated by cargo-arxml.
pub trait ServiceDefinition: Send + Sync + 'static {
    const SERVICE_ID: ServiceId;
    const MAJOR_VERSION: MajorVersion;
    const MINOR_VERSION: MinorVersion;

    /// Human-readable service name (from ARXML short-name)
    fn service_name() -> &'static str;
}

/// Handle for managing a service instance lifecycle
#[derive(Debug)]
pub struct ServiceHandle {
    pub service_id: ServiceId,
    pub instance_id: InstanceId,
    state: ServiceState,
}

impl ServiceHandle {
    /// Create a new `ServiceHandle` in the `Idle` state.
    pub fn new(service_id: ServiceId, instance_id: InstanceId) -> Self {
        Self {
            service_id,
            instance_id,
            state: ServiceState::Idle,
        }
    }

    /// Return the current state of this handle.
    pub fn state(&self) -> &ServiceState {
        &self.state
    }

    /// Transition to a new state.
    pub fn set_state(&mut self, state: ServiceState) {
        self.state = state;
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServiceState {
    /// Not yet offered/requested
    Idle,
    /// Service is being offered (skeleton side)
    Offered,
    /// Service has been found (proxy side)
    Available,
    /// Service was available but is now gone
    Unavailable,
}

/// Availability handler callback type
pub type AvailabilityHandler = Box<dyn Fn(ServiceState) + Send + Sync>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_service_handle_state_transitions() {
        let mut handle = ServiceHandle::new(ServiceId(0x1234), InstanceId(0x0001));
        assert_eq!(handle.state(), &ServiceState::Idle);

        handle.set_state(ServiceState::Offered);
        assert_eq!(handle.state(), &ServiceState::Offered);

        handle.set_state(ServiceState::Available);
        assert_eq!(handle.state(), &ServiceState::Available);

        handle.set_state(ServiceState::Unavailable);
        assert_eq!(handle.state(), &ServiceState::Unavailable);
    }
}