mirror of
https://github.com/rust-lang/rust.git
synced 2025-06-21 20:17:55 +00:00

This removes all mutex/atomics based workarounds for non-monotonic clocks and makes the previously panicking methods saturating instead. Effectively this moves the monotonization from `Instant` construction to the comparisons. This has some observable effects, especially on platforms without monotonic clocks: * Incorrectly ordered Instant comparisons no longer panic. This may hide some programming errors until someone actually looks at the resulting `Duration` * `checked_duration_since` will now return `None` in more cases. Previously it only happened when one compared instants obtained in the wrong order or manually created ones. Now it also does on backslides. The upside is reduced complexity and lower overhead of `Instant::now`.
47 lines
1.3 KiB
Rust
47 lines
1.3 KiB
Rust
use super::abi::usercalls;
|
|
use crate::time::Duration;
|
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
|
|
pub struct Instant(Duration);
|
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
|
|
pub struct SystemTime(Duration);
|
|
|
|
pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::from_secs(0));
|
|
|
|
impl Instant {
|
|
pub fn now() -> Instant {
|
|
Instant(usercalls::insecure_time())
|
|
}
|
|
|
|
pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
|
|
self.0.checked_sub(other.0)
|
|
}
|
|
|
|
pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
|
|
Some(Instant(self.0.checked_add(*other)?))
|
|
}
|
|
|
|
pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
|
|
Some(Instant(self.0.checked_sub(*other)?))
|
|
}
|
|
}
|
|
|
|
impl SystemTime {
|
|
pub fn now() -> SystemTime {
|
|
SystemTime(usercalls::insecure_time())
|
|
}
|
|
|
|
pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
|
|
self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0)
|
|
}
|
|
|
|
pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
|
|
Some(SystemTime(self.0.checked_add(*other)?))
|
|
}
|
|
|
|
pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
|
|
Some(SystemTime(self.0.checked_sub(*other)?))
|
|
}
|
|
}
|