scsys_core/state/
nstate.rs

1/*
2    Appellation: state <module>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5use super::RawStateKind;
6use core::marker::PhantomData;
7
8/// [`StateBase`] is an abstract object that allows a particular _kind_ of state to be
9/// associated with some generic state `Q`
10#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
11#[cfg_attr(
12    feature = "serde",
13    derive(serde::Deserialize, serde::Serialize),
14    serde(default)
15)]
16pub struct StateBase<Q, K> {
17    pub(crate) state: Q,
18    pub(crate) _kind: PhantomData<K>,
19}
20
21impl<K, Q> StateBase<Q, K>
22where
23    K: RawStateKind,
24{
25    /// returns a new instance of [`StateBase`] with the given value
26    pub const fn new(state: Q) -> Self {
27        Self {
28            state,
29            _kind: PhantomData::<K>,
30        }
31    }
32    /// returns a new instance of [`StateBase`] using the output of the given function `F`
33    pub fn new_with<F>(f: F) -> Self
34    where
35        F: FnOnce() -> Q,
36    {
37        Self::new(f())
38    }
39    #[allow(clippy::should_implement_trait)]
40    /// returns a new instance of [`StateBase`] using the logical default for the type `Q`
41    pub fn default() -> Self
42    where
43        Q: Default,
44    {
45        Self::new(Default::default())
46    }
47    /// returns a reference to the state
48    pub const fn get(&self) -> &Q {
49        &self.state
50    }
51    /// returns a mutable reference to the state
52    pub const fn get_mut(&mut self) -> &mut Q {
53        &mut self.state
54    }
55    /// returns true if the state is of the specified kind
56    pub fn is_kind<R>(&self) -> bool
57    where
58        R: 'static,
59    {
60        use core::any::TypeId;
61        TypeId::of::<K>() == TypeId::of::<R>()
62    }
63}