event_simulation/
borrowed.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use std::ops::Deref;

use super::{Simulation, SimulationInfo};

/// 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> Simulation for BorrowedSimulation<'_, Info> {
    type StateLoadingError = Info::StateLoadingError;
    type AccessData = Info::AccessData;
    type LoadData = Info::LoadData;
    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 reload(&mut self, data: Info::LoadData) -> Result<(), Info::StateLoadingError> {
        self.state = self.info.load_state(data)?;
        Ok(())
    }

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

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

    #[inline]
    unsafe fn call(&mut self, event: Info::Event) {
        unsafe { self.info.call(&mut 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)
    }

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