event_simulation/
borrowed.rs

1use std::ops::Deref;
2
3use super::{Simulation, SimulationInfo};
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> Simulation for BorrowedSimulation<'_, Info> {
47    type StateLoadingError = Info::StateLoadingError;
48    type AccessData = Info::AccessData;
49    type LoadData = Info::LoadData;
50    type Event = Info::Event;
51    type EventContainer<'a> = Info::EventContainer<'a>
52    where
53        Self: 'a;
54
55    #[inline]
56    fn data(&self) -> &Info::AccessData {
57        unsafe { self.info.data(&self.state) }
58    }
59
60    #[inline]
61    fn reload(&mut self, data: Info::LoadData) -> Result<(), Info::StateLoadingError> {
62        self.state = self.info.load_state(data)?;
63        Ok(())
64    }
65
66    #[inline]
67    fn callables(&self) -> Info::EventContainer<'_> {
68        Info::callables(&self.state)
69    }
70
71    #[inline]
72    fn callable(&self, event: Info::Event) -> bool {
73        Info::callable(&self.state, event)
74    }
75
76    #[inline]
77    unsafe fn call(&mut self, event: Info::Event) {
78        unsafe { self.info.call(&mut self.state, event) }
79    }
80
81    #[inline]
82    fn revertables(&self) -> Info::EventContainer<'_> {
83        Info::revertables(&self.state)
84    }
85
86    #[inline]
87    fn revertable(&self, event: Info::Event) -> bool {
88        Info::revertable(&self.state, event)
89    }
90
91    #[inline]
92    unsafe fn revert(&mut self, event: Info::Event) {
93        self.info.revert(&mut self.state, event)
94    }
95}