1#[derive(Clone, Copy, Debug)]
7pub struct CurrentPrevious<T> {
8 current: T,
9 previous: Option<T>
10}
11
12impl <T> CurrentPrevious<T> {
13 pub fn new(initial: T) -> Self {
26 return Self {
27 current: initial,
28 previous: None
29 };
30 }
31
32 pub fn current(&self) -> &T {
34 return &self.current;
35 }
36
37 pub fn previous(&self) -> Option<&T> {
39 return self.previous.as_ref();
40 }
41
42 pub fn update(&mut self, new: T) {
60 self.previous = Some(std::mem::replace(&mut self.current, new));
61 }
62
63 pub fn reset(&mut self, new: T) {
81 *self = Self::new(new);
82 }
83
84 pub fn clear_previous(&mut self) {
106 self.previous = None;
107 }
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113
114 #[test]
115 fn set_current() {
116 let current_previous = CurrentPrevious::new(0);
117
118 assert_eq!(current_previous.current(), &0);
119 assert_eq!(current_previous.previous(), None);
120 }
121
122 #[test]
123 fn set_current_twice() {
124 let mut current_previous = CurrentPrevious::new(0);
125
126 current_previous.update(1);
127
128 assert_eq!(current_previous.current(), &1);
129 assert_eq!(current_previous.previous(), Some(&0));
130 }
131
132 #[test]
133 fn set_current_thrice() {
134 let mut current_previous = CurrentPrevious::new(0);
135
136 current_previous.update(1);
137
138 current_previous.update(2);
139
140 assert_eq!(current_previous.current(), &2);
141 assert_eq!(current_previous.previous(), Some(&1));
142 }
143
144 #[test]
145 fn clone() {
146 let current_previous = CurrentPrevious::new(0);
147
148 let mut cloned_current_previous = current_previous.clone();
149
150 assert_eq!(current_previous.current(), &0);
151 assert_eq!(current_previous.previous(), None);
152
153 assert_eq!(cloned_current_previous.current(), &0);
154 assert_eq!(cloned_current_previous.previous(), None);
155
156 cloned_current_previous.update(1);
157
158 assert_eq!(current_previous.current(), &0);
159 assert_eq!(current_previous.previous(), None);
160
161 assert_eq!(cloned_current_previous.current(), &1);
162 assert_eq!(cloned_current_previous.previous(), Some(&0));
163 }
164
165 #[test]
166 fn debug_print() {
167 let mut current_previous = CurrentPrevious::new(0);
168
169 assert_eq!(format!("{current_previous:?}"), "CurrentPrevious { current: 0, previous: None }");
170
171 current_previous.update(1);
172
173 assert_eq!(format!("{current_previous:?}"), "CurrentPrevious { current: 1, previous: Some(0) }");
174 }
175
176 #[test]
177 fn reset() {
178 let mut current_previous = CurrentPrevious::new(0);
179
180 current_previous.reset(1);
181
182 assert_eq!(current_previous.current(), &1);
183 assert_eq!(current_previous.previous(), None);
184 }
185}