event-simulation 0.2.0

A library for event based simulation of application state
Documentation
use std::ops::Deref;

use crate::{Simulation, SimulationInfo, SimulationState};

/// A borrowed simulation that holds an immutable reference to the simulation info
/// and owns the simulation state.
pub struct BorrowedSimulation<'a, Info: SimulationInfo> {
    info: &'a Info,
    /// The simulation state.
    pub state: Info::State,
}

impl<'a, Info: SimulationInfo> BorrowedSimulation<'a, Info> {
    /// Creates a new `BorrowedSimulation` which belongs to the specified `info`.
    pub fn new(info: &'a Info) -> Self {
        let state = info.default_state();
        Self { info, state }
    }

    /// Loads a new `BorrowedSimulation` from `data` which belongs to the specified `info`.
    pub fn from_data(
        info: &'a Info,
        data: Info::LoadData,
    ) -> Result<Self, Info::StateLoadingError> {
        let state = info.load_state(data)?;
        Ok(Self { info, state })
    }
}

impl<Info: SimulationInfo + Clone> Clone for BorrowedSimulation<'_, Info> {
    fn clone(&self) -> Self {
        let info = &self.info;
        let state = unsafe { info.clone_state(&self.state) };
        Self { info, state }
    }
}

impl<Info: SimulationInfo> Deref for BorrowedSimulation<'_, Info> {
    type Target = Info;

    fn deref(&self) -> &Info {
        self.info
    }
}

impl<Info: SimulationInfo> SimulationState for BorrowedSimulation<'_, Info> {
    type AccessData = Info::AccessData;
    type Event = Info::Event;
    type EventContainer<'a>
        = Info::EventContainer<'a>
    where
        Self: 'a;

    #[inline]
    fn data(&self) -> &Info::AccessData {
        unsafe { self.info.data(&self.state) }
    }

    #[inline]
    fn callables(&self) -> Info::EventContainer<'_> {
        Info::callables(&self.state)
    }

    #[inline]
    fn callable(&self, event: Info::Event) -> bool {
        Info::callable(&self.state, event)
    }

    #[inline]
    fn revertables(&self) -> Info::EventContainer<'_> {
        Info::revertables(&self.state)
    }

    #[inline]
    fn revertable(&self, event: Info::Event) -> bool {
        Info::revertable(&self.state, event)
    }
}

impl<Info: SimulationInfo> Simulation for BorrowedSimulation<'_, Info> {
    type StateLoadingError = Info::StateLoadingError;
    type LoadData = Info::LoadData;

    #[inline]
    fn reload(&mut self, data: Info::LoadData) -> Result<(), Info::StateLoadingError> {
        self.state = self.info.load_state(data)?;
        Ok(())
    }

    #[inline]
    unsafe fn call(&mut self, event: Info::Event) {
        unsafe { self.info.call(&mut self.state, event) }
    }

    #[inline]
    unsafe fn revert(&mut self, event: Info::Event) {
        unsafe { self.info.revert(&mut self.state, event) }
    }
}