Skip to main content

event_simulation/
borrowed.rs

1use std::ops::Deref;
2
3use crate::{Simulation, SimulationInfo, SimulationState};
4
5/// A borrowed simulation that holds an immutable reference to the simulation info
6/// and owns the simulation state.
7pub struct BorrowedSimulation<'a, Info: SimulationInfo> {
8    info: &'a Info,
9    /// The simulation state.
10    pub state: Info::State,
11}
12
13impl<'a, Info: SimulationInfo> BorrowedSimulation<'a, Info> {
14    /// Creates a new `BorrowedSimulation` which belongs to the specified `info`.
15    pub fn new(info: &'a Info) -> Self {
16        let state = info.default_state();
17        Self { info, state }
18    }
19
20    /// Loads a new `BorrowedSimulation` from `data` which belongs to the specified `info`.
21    pub fn from_data(
22        info: &'a Info,
23        data: Info::LoadData,
24    ) -> Result<Self, Info::StateLoadingError> {
25        let state = info.load_state(data)?;
26        Ok(Self { info, state })
27    }
28}
29
30impl<Info: SimulationInfo + Clone> Clone for BorrowedSimulation<'_, Info> {
31    fn clone(&self) -> Self {
32        let info = &self.info;
33        let state = unsafe { info.clone_state(&self.state) };
34        Self { info, state }
35    }
36}
37
38impl<Info: SimulationInfo> Deref for BorrowedSimulation<'_, Info> {
39    type Target = Info;
40
41    fn deref(&self) -> &Info {
42        self.info
43    }
44}
45
46impl<Info: SimulationInfo> SimulationState for BorrowedSimulation<'_, Info> {
47    type AccessData = Info::AccessData;
48    type Event = Info::Event;
49    type EventContainer<'a>
50        = Info::EventContainer<'a>
51    where
52        Self: 'a;
53
54    #[inline]
55    fn data(&self) -> &Info::AccessData {
56        unsafe { self.info.data(&self.state) }
57    }
58
59    #[inline]
60    fn callables(&self) -> Info::EventContainer<'_> {
61        Info::callables(&self.state)
62    }
63
64    #[inline]
65    fn callable(&self, event: Info::Event) -> bool {
66        Info::callable(&self.state, event)
67    }
68
69    #[inline]
70    fn revertables(&self) -> Info::EventContainer<'_> {
71        Info::revertables(&self.state)
72    }
73
74    #[inline]
75    fn revertable(&self, event: Info::Event) -> bool {
76        Info::revertable(&self.state, event)
77    }
78}
79
80impl<Info: SimulationInfo> Simulation for BorrowedSimulation<'_, Info> {
81    type StateLoadingError = Info::StateLoadingError;
82    type LoadData = Info::LoadData;
83
84    #[inline]
85    fn reload(&mut self, data: Info::LoadData) -> Result<(), Info::StateLoadingError> {
86        self.state = self.info.load_state(data)?;
87        Ok(())
88    }
89
90    #[inline]
91    unsafe fn call(&mut self, event: Info::Event) {
92        unsafe { self.info.call(&mut self.state, event) }
93    }
94
95    #[inline]
96    unsafe fn revert(&mut self, event: Info::Event) {
97        unsafe { self.info.revert(&mut self.state, event) }
98    }
99}