magicstatemachines/
state_trait.rs1use core::any::TypeId;
2
3#[cfg(feature = "dynZST")]
4#[doc(hidden)]
5pub trait StateTraitZst: dynzst::IsZeroSized {}
6
7#[cfg(feature = "dynZST")]
8impl<T> StateTraitZst for T where T: dynzst::IsZeroSized {}
9
10#[cfg(not(feature = "dynZST"))]
11#[doc(hidden)]
12pub trait StateTraitZst {}
13
14#[cfg(not(feature = "dynZST"))]
15impl<T> StateTraitZst for T {}
16
17pub trait StateTrait: StateTraitZst + 'static {
57 fn type_name(&self) -> &'static str;
63
64 #[doc(hidden)]
65 fn type_id(&self) -> TypeId;
66
67 #[doc(hidden)]
68 fn erased_state() -> &'static dyn StateTrait
69 where
70 Self: Sized;
71}
72
73impl<T> StateTrait for T
74where
75 T: crate::StateMarker + StateTraitZst + 'static,
76{
77 fn type_name(&self) -> &'static str {
78 core::any::type_name::<T>()
79 }
80
81 fn type_id(&self) -> TypeId {
82 TypeId::of::<T>()
83 }
84
85 fn erased_state() -> &'static dyn StateTrait {
86 <T as crate::StateMarker>::erased_state()
87 }
88}
89
90#[doc(hidden)]
91pub trait ConcreteStateTrait:
92 StateTrait + crate::StateMarker<Kind = crate::ConcreteStateKind>
93{
94 fn erased_state() -> &'static dyn StateTrait
95 where
96 Self: Sized;
97}
98
99#[cfg(feature = "dynZST")]
100#[doc(hidden)]
101pub type ErasedState = dynzst::DynZSTBox<dyn StateTrait>;
102
103#[cfg(not(feature = "dynZST"))]
104#[doc(hidden)]
105pub type ErasedState = &'static dyn StateTrait;
106
107#[cfg(feature = "dynZST")]
108pub(crate) fn erased_state<T>() -> ErasedState
109where
110 T: ConcreteStateTrait,
111{
112 dynzst::DynZSTBox::with_dyn(<T as ConcreteStateTrait>::erased_state())
113}
114
115#[cfg(not(feature = "dynZST"))]
116pub(crate) fn erased_state<T>() -> ErasedState
117where
118 T: ConcreteStateTrait,
119{
120 <T as ConcreteStateTrait>::erased_state()
121}
122
123#[cfg(feature = "dynZST")]
124#[doc(hidden)]
125pub fn clone_erased(state: &ErasedState) -> ErasedState {
126 dynzst::DynZSTBox::with_dyn(&**state)
127}
128
129#[cfg(not(feature = "dynZST"))]
130#[doc(hidden)]
131pub fn clone_erased(state: &ErasedState) -> ErasedState {
132 *state
133}
134
135pub(crate) fn is_state<T>(state: &ErasedState) -> bool
136where
137 T: StateTrait,
138{
139 state.type_id() == TypeId::of::<T>()
140}
141
142pub(crate) fn static_erased_state<T>() -> ErasedState
143where
144 T: StateTrait,
145{
146 #[cfg(feature = "dynZST")]
147 {
148 dynzst::DynZSTBox::with_dyn(T::erased_state())
149 }
150 #[cfg(not(feature = "dynZST"))]
151 {
152 T::erased_state()
153 }
154}