time_utils/
lib.rs

1// Copyright 2015-2020 Parity Technologies (UK) Ltd.
2// This file is part of Tetsy Vapory.
3
4// Tetsy Vapory is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Tetsy Vapory is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Tetsy Vapory.  If not, see <http://www.gnu.org/licenses/>.
16
17use std::time::{Duration, SystemTime, UNIX_EPOCH};
18
19/// Temporary trait for `checked operations` on SystemTime until these are available in the standard library
20pub trait CheckedSystemTime {
21	/// Returns `Some<SystemTime>` when the result less or equal to `i32::max_value` to prevent `SystemTime` to panic because
22	/// it is platform specific, possible representations are i32, i64, u64 or Duration. `None` otherwise
23	fn checked_add(self, _d: Duration) -> Option<SystemTime>;
24	/// Returns `Some<SystemTime>` when the result is successful and `None` when it is not
25	fn checked_sub(self, _d: Duration) -> Option<SystemTime>;
26}
27
28impl CheckedSystemTime for SystemTime {
29	fn checked_add(self, dur: Duration) -> Option<SystemTime> {
30		let this_dur = self.duration_since(UNIX_EPOCH).ok()?;
31		let total_time = this_dur.checked_add(dur)?;
32
33		if total_time.as_secs() <= i32::max_value() as u64 {
34			Some(self + dur)
35		} else {
36			None
37		}
38	}
39
40	fn checked_sub(self, dur: Duration) -> Option<SystemTime> {
41		let this_dur = self.duration_since(UNIX_EPOCH).ok()?;
42		let total_time = this_dur.checked_sub(dur)?;
43
44		if total_time.as_secs() <= i32::max_value() as u64 {
45			Some(self - dur)
46		} else {
47			None
48		}
49	}
50}
51
52#[cfg(test)]
53mod tests {
54    #[test]
55    fn it_works() {
56		use super::CheckedSystemTime;
57		use std::time::{Duration, SystemTime, UNIX_EPOCH};
58
59		assert!(CheckedSystemTime::checked_add(UNIX_EPOCH, Duration::new(i32::max_value() as u64 + 1, 0)).is_none());
60		assert!(CheckedSystemTime::checked_add(UNIX_EPOCH, Duration::new(i32::max_value() as u64, 0)).is_some());
61		assert!(CheckedSystemTime::checked_add(UNIX_EPOCH, Duration::new(i32::max_value() as u64 - 1, 1_000_000_000)).is_some());
62
63		assert!(CheckedSystemTime::checked_sub(UNIX_EPOCH, Duration::from_secs(120)).is_none());
64		assert!(CheckedSystemTime::checked_sub(SystemTime::now(), Duration::from_secs(1000)).is_some());
65	}
66}