npc_engine_core/
state_diff.rs

1/*
2 *  SPDX-License-Identifier: Apache-2.0 OR MIT
3 *  © 2020-2022 ETH Zurich and other contributors, see AUTHORS.txt for details
4 */
5
6use std::{fmt, mem, ops::Deref};
7
8use crate::Domain;
9
10/// A joint reference to an initial state and a difference to this state.
11pub struct StateDiffRef<'a, D: Domain> {
12    /// Initial state
13    pub initial_state: &'a D::State,
14    /// Difference to the initial state
15    pub diff: &'a D::Diff,
16}
17impl<D: Domain> Copy for StateDiffRef<'_, D> {}
18impl<D: Domain> Clone for StateDiffRef<'_, D> {
19    fn clone(&self) -> Self {
20        StateDiffRef::new(self.initial_state, self.diff)
21    }
22}
23impl<'a, D: Domain> StateDiffRef<'a, D> {
24    pub fn new(initial_state: &'a D::State, diff: &'a D::Diff) -> Self {
25        StateDiffRef {
26            initial_state,
27            diff,
28        }
29    }
30}
31
32impl<D: Domain> fmt::Debug for StateDiffRef<'_, D>
33where
34    D::State: fmt::Debug,
35    D::Diff: fmt::Debug,
36{
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.debug_struct("SnapshotDiffRef")
39            .field("Snapshot", self.initial_state)
40            .field("Diff", self.diff)
41            .finish()
42    }
43}
44
45/// A joint reference to an initial state and a difference to this state, where the difference is mutable.
46pub struct StateDiffRefMut<'a, D: Domain> {
47    /// Initial state
48    pub initial_state: &'a D::State,
49    /// Difference (mutable) to the initial state
50    pub diff: &'a mut D::Diff,
51}
52impl<'a, D: Domain> StateDiffRefMut<'a, D> {
53    pub fn new(initial_state: &'a D::State, diff: &'a mut D::Diff) -> Self {
54        StateDiffRefMut {
55            initial_state,
56            diff,
57        }
58    }
59}
60
61impl<'a, D: Domain> Deref for StateDiffRefMut<'a, D> {
62    type Target = StateDiffRef<'a, D>;
63
64    fn deref(&self) -> &Self::Target {
65        // Safety: StateDiffRef and StateDiffRefMut have the same memory layout
66        // and casting from mutable to immutable is always safe
67        unsafe { mem::transmute(self) }
68    }
69}