1pub mod timer {
2
3 use std::{io::Write, thread, time::Duration};
4
5
6 #[derive(Clone, Copy, Debug)]
7
8 pub struct TimerStruct {
9
10 pub duration: u32,
11
12 pub hours: u32,
13
14 pub minutes: u32,
15
16 pub seconds: u32,
17
18 }
19
20
21 impl TimerStruct {
22
23 pub fn new(hours: u32, minutes: u32, seconds: u32) -> Result<TimerStruct, &'static str> {
24
25 let duration = (hours * 3600) + (minutes * 60) + seconds;
26
27 if duration == 0 {
28
29 return Err("Duration need to be 1 or more seconds.");
30
31 }
32
33
34 Ok(TimerStruct {
35
36 duration,
37
38 hours,
39
40 minutes,
41
42 seconds,
43
44 })
45
46 }
47
48
49 pub fn start_timer<W: Write>(&self, writer: &mut W) {
50
51 let mut current_duration = self.duration;
52
53 let one_second = Duration::from_secs(1);
54
55
56 loop {
57
58 let display_hours = current_duration / 3600;
61
62 let remaining_seconds_after_hours = current_duration % 3600;
63
64 let display_minutes = remaining_seconds_after_hours / 60;
65
66 let display_seconds = remaining_seconds_after_hours % 60;
67
68
69 let time_display_string =
70
71 format!("{}:{}:{}", display_hours, display_minutes, display_seconds);
72
73
74 if current_duration == 0 {
75
76 writeln!(writer, "{}", time_display_string).unwrap();
79
80 break;
81
82 } else {
83
84 write!(writer, "{}\r", time_display_string).unwrap();
87
88 writer.flush().unwrap(); }
91
92
93 thread::sleep(one_second);
94
95 current_duration -= 1;
96
97 }
98
99 }
100
101 }
102
103}
104
105
106pub use timer::TimerStruct;
107
108pub mod stopwatch {
109 use std::{io::Write,thread, time::Duration};
110
111 #[derive(Clone, Debug)]
112 pub enum StopwatchStatus {
113 Stopped,
114 Running,
115 }
116
117 #[derive(Debug, Clone)]
118 pub struct StopwatchStruct<T>
119 where T: Fn(u32),
120 {
121 pub current_time: u32,
122 pub status: StopwatchStatus,
123 pub operation_on_stop: T,
124 }
125
126 impl<T> StopwatchStruct<T>
127 where T: Fn(u32),
128 {
129 pub fn new(operation_on_stop: T) -> StopwatchStruct<T> {
130 StopwatchStruct {
131 current_time: 0,
132 status: StopwatchStatus::Running,
133 operation_on_stop,
134 }
135 }
136
137 pub fn start_timer<W: Write>(&mut self, writer: &mut W) {
138 loop {
139 match self.status {
140 StopwatchStatus::Stopped => {
141 (self.operation_on_stop)(self.current_time);
142 break;
143 },
144 StopwatchStatus::Running => (),
145 }
146
147 let hours = self.current_time / 3600;
148 let mut remaining = self.current_time % 3600;
149 let minutes = remaining / 60;
150 remaining %= 60;
151
152 let output_format = format!("{}:{}:{}", hours, minutes, remaining);
153
154 if self.current_time == 0 {
155 write!(writer, "{}", output_format).unwrap();
156 }
157
158 thread::sleep(Duration::from_secs(1));
159
160 self.current_time += 1;
161
162 write!(writer, "{}\r", output_format).unwrap();
163
164
165 }
166 }
167 }
168}