scsys_core/state/impls/
impl_state.rs1use crate::state::{RawState, State};
6impl<Q> State<Q> {
8 pub fn new() -> Self
10 where
11 Q: Default,
12 {
13 Self(Q::default())
14 }
15 pub fn from_value(id: Q) -> Self {
17 Self(id)
18 }
19 #[cfg(feature = "rand")]
20 pub fn random() -> Self
21 where
22 rand_distr::StandardUniform: rand_distr::Distribution<Q>,
23 {
24 use rand::Rng;
25 let mut rng = rand::rng();
26 Self::from_value(rng.random())
27 }
28 pub const fn get(&self) -> &Q {
30 &self.0
31 }
32 pub fn get_mut(&mut self) -> &mut Q {
34 &mut self.0
35 }
36 pub fn into_inner(self) -> Q {
38 self.0
39 }
40 pub fn replace(&mut self, id: Q) -> Q {
42 core::mem::replace(self.get_mut(), id)
43 }
44 pub fn set(&mut self, id: Q) -> &mut Self {
46 *self.get_mut() = id;
47 self
48 }
49 pub fn take(&mut self) -> Q
51 where
52 Q: Default,
53 {
54 core::mem::take(self.get_mut())
55 }
56 pub fn with<U>(self, id: U) -> State<U> {
58 State(id)
59 }
60 pub fn map<U, F>(self, f: F) -> State<U>
62 where
63 F: FnOnce(Q) -> U,
64 {
65 State(f(self.0))
66 }
67
68 pub fn to_owned(self) -> State<Q>
69 where
70 Q: Clone,
71 {
72 State(self.0.clone())
73 }
74 pub const fn view(&self) -> State<&Q> {
76 State(&self.0)
77 }
78 pub const fn view_mut(&mut self) -> State<&mut Q> {
80 State(&mut self.0)
81 }
82}
83
84impl<Q> RawState for State<Q> {
85 type Item = Q;
86
87 seal!();
88}
89
90impl<Q> AsRef<Q> for State<Q> {
91 fn as_ref(&self) -> &Q {
92 &self.0
93 }
94}
95
96impl<Q> AsMut<Q> for State<Q> {
97 fn as_mut(&mut self) -> &mut Q {
98 &mut self.0
99 }
100}
101
102impl<Q> core::borrow::Borrow<Q> for State<Q> {
103 fn borrow(&self) -> &Q {
104 &self.0
105 }
106}
107
108impl<Q> core::borrow::BorrowMut<Q> for State<Q> {
109 fn borrow_mut(&mut self) -> &mut Q {
110 &mut self.0
111 }
112}
113
114impl<Q> core::ops::Deref for State<Q> {
115 type Target = Q;
116
117 fn deref(&self) -> &Self::Target {
118 &self.0
119 }
120}
121
122impl<Q> core::ops::DerefMut for State<Q> {
123 fn deref_mut(&mut self) -> &mut Self::Target {
124 &mut self.0
125 }
126}
127
128fmt_wrapper! {
129 State<Q> {
130 Binary("{:b}"),
131 Debug("{:?}"),
132 Display("{}"),
133 LowerExp("{:e}"),
134 LowerHex("{:x}"),
135 Octal("{:o}"),
136 UpperExp("{:E}"),
137 UpperHex("{:X}")
138 }
139}