1use std::ops::AddAssign;
2use std::ops::Sub;
3use std::time::{Duration, Instant};
4
5#[derive(Copy, Clone, Debug)]
10pub struct StopWatch {
11 last_start_time: Instant,
12 running: bool,
13 duration: Duration,
14}
15
16impl Default for StopWatch {
17 fn default() -> Self {
18 Self::new()
19 }
20}
21
22impl StopWatch {
23 pub fn new() -> StopWatch {
25 StopWatch {
26 last_start_time: Instant::now(),
27 running: true,
28 duration: Duration::new(0, 0),
29 }
30 }
31 pub fn restart(&mut self) {
33 self.last_start_time = Instant::now();
34 self.running = true;
35 self.duration = Duration::new(0, 0);
36 }
37 pub fn stop(mut self) -> Duration {
39 self.running = false;
40 self.duration
41 .add_assign(Instant::now().sub(self.last_start_time));
42 self.duration
43 }
44 pub fn pause(&mut self) {
46 self.running = false;
47 self.duration
48 .add_assign(Instant::now().sub(self.last_start_time))
49 }
50 pub fn resume(&mut self) {
52 self.running = true;
53 self.last_start_time = Instant::now();
54 }
55 pub fn elapsed_time(&self) -> Duration {
57 self.duration
58 }
59 pub fn is_running(&self) -> bool {
61 self.running
62 }
63}