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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use std::time::Duration;
use std::time::Instant;
use std::thread;
#[derive(Debug, PartialEq, Clone)]
pub struct Timer {
time: Duration,
time_left: Duration,
time_elapse: Instant,
}
impl Timer {
pub fn new(time: Duration) -> Self {
Self{
time,
time_left: Duration::default(),
time_elapse: Instant::now()
}
}
pub fn set(&mut self, time: Duration) {
self.time = time;
}
pub fn start(&mut self) {
self.time_left = self.time;
self.time_elapse = Instant::now();
}
pub fn update(&mut self) {
self.time_left = self.time_left.saturating_sub(
self.time_elapse.elapsed()
);
self.time_elapse = Instant::now();
}
pub fn until_done(&mut self) {
self.start();
while !self.done(){
self.update();
thread::sleep(Duration::from_millis(1));
}
}
pub fn time(&self) -> Duration {
self.time
}
pub fn done(&self) -> bool {
self.time_left.is_zero()
}
pub fn left(&self) -> Duration {
self.time_left
}
}
impl Default for Timer {
fn default() -> Self {
Self {
time: Duration::default(),
time_left: Duration::default(),
time_elapse: Instant::now(),
}
}
}
impl std::ops::Add<Duration> for Timer {
type Output = Self;
fn add(self, rhs: Duration) -> Self::Output {
Self {
time: self.time + rhs,
time_left: self.time_left + rhs,
time_elapse: self.time_elapse
}
}
}
impl std::ops::Sub<Duration> for Timer {
type Output = Self;
fn sub(self, rhs: Duration) -> Self::Output {
Self {
time: self.time - rhs,
time_left: self.time_left - rhs,
time_elapse: self.time_elapse
}
}
}