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
//! Simple timer

use std::time::Duration;
use std::time::Instant;
use std::thread;

/// A simple timer made with the std library
#[derive(Debug, PartialEq, Clone)]
pub struct Timer {
	time: Duration,
	time_left: Duration,
	time_elapse: Instant,
}

impl Timer {
	/// Creates a new [`Timer`].
	///
	/// use `default()` for a 0 initialized.
	pub fn new(time: Duration) -> Self {
		Self{
			time,
			time_left: Duration::default(),
			time_elapse: Instant::now()
		}
	}
	/// Sets the time.
	pub fn set(&mut self, time: Duration) {
		self.time = time;
	}
	
	/// Starts or resets the [`Timer`].
	pub fn start(&mut self) {
		self.time_left = self.time;
		self.time_elapse = Instant::now();
	}
	
	/// updates the [`Timer`].
	/// Make sure to `start()` before updates.
	/// 
	/// may not be accuarate if is called again before doing something else,
	/// use `until_done()` instead in that case.
	pub fn update(&mut self) {
		self.time_left = self.time_left.saturating_sub(
			self.time_elapse.elapsed()
		);
		self.time_elapse = Instant::now();
	}
	
	/// Updates every 1ms until its done, locking the thread.
	///
	/// will do `start()`
	pub fn until_done(&mut self) {
		self.start();
		while !self.done(){
			self.update();
			thread::sleep(Duration::from_millis(1));
		}
	}
	
	/// Returns the time set.
	pub fn time(&self) -> Duration {
		self.time
	}
	
	/// `true` if the timer is done or zero.
	pub fn done(&self) -> bool {
		self.time_left.is_zero()
	}
	
	/// Return the time left until is done.
	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
		}
	}
}