1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use chrono::{DateTime, Duration, Local};
#[derive(Clone, Debug)]
pub struct Timer {
pub remaining: Duration,
pub total: Duration,
pub start_moments: Vec<DateTime<Local>>,
pub pause_moments: Vec<DateTime<Local>>,
pub paused: bool,
}
impl Timer {
pub fn new(duration: Duration) -> Self {
Self {
remaining: duration,
total: duration,
start_moments: Vec::new(),
pause_moments: Vec::new(),
paused: true,
}
}
pub fn read(&self) -> Duration {
if self.paused {
self.remaining
} else {
self.remaining - (Local::now() - self.last_start())
}
}
pub fn pause_or_resume(&mut self) {
if self.paused {
self.resume();
} else {
self.pause();
}
}
pub fn start_moment(&self) -> DateTime<Local> {
self.start_moments[0]
}
pub fn stop_moment(&self) -> DateTime<Local> {
self.pause_moments[self.pause_moments.len() - 1]
}
fn last_start(&self) -> DateTime<Local> {
self.start_moments[self.start_moments.len() - 1]
}
pub fn pause(&mut self) {
let moment = Local::now();
self.pause_moments.push(moment);
self.remaining = self.remaining - (moment - self.last_start());
self.paused = true;
}
pub fn resume(&mut self) {
self.start_moments.push(Local::now());
self.paused = false;
}
}