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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
use core::sync::atomic::{AtomicI64, Ordering};
/// A stable equivalent to [`core::time::Duration`]
#[crate::stabby]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Duration {
/// The number of seconds elapsed.
pub secs: u64,
/// The number of subsecond nanos elapsed.
pub nanos: u32,
}
impl Duration {
/// Construct a new [`Duration`].
pub const fn new(secs: u64, subsec_nanos: u32) -> Self {
Self {
secs,
nanos: subsec_nanos,
}
}
/// Construct a new [`Duration`].
pub const fn from_millis(millis: u64) -> Self {
Self {
secs: millis / 1000,
nanos: ((millis % 1000) * 1000000) as u32,
}
}
/// Construct a new [`Duration`].
pub const fn from_micros(micros: u64) -> Self {
Self {
secs: micros / 1000000,
nanos: ((micros % 1000000) * 1000) as u32,
}
}
/// Construct a new [`Duration`].
///
/// # Panics
/// if `secs` is negative.
#[cfg(feature = "std")]
pub fn from_secs_f64(secs: f64) -> Self {
assert!(secs >= 0.);
Self {
secs: secs.floor() as u64,
nanos: ((secs % 1.) * 1_000_000_000.) as u32,
}
}
/// Returns the number of seconds in the duration.
pub const fn as_secs(&self) -> u64 {
self.secs
}
/// Returns the total number of nanoseconds in the duration.
pub const fn as_nanos(&self) -> u128 {
self.secs as u128 * 1_000_000_000 + self.nanos as u128
}
/// Returns the number of seconds in the duration, including sub-seconds.
pub fn as_secs_f64(&self) -> f64 {
self.as_nanos() as f64 / 1_000_000_000.
}
/// Returns the number of nanoseconds after the last second of the duration.
pub const fn subsec_nanos(&self) -> u32 {
self.nanos
}
/// Returns the number of microseconds after the last second of the duration.
pub const fn subsec_micros(&self) -> u32 {
self.subsec_nanos() / 1000
}
/// Returns the number of milliseconds after the last second of the duration.
pub const fn subsec_millis(&self) -> u32 {
self.subsec_nanos() / 1000000
}
}
impl core::ops::AddAssign for Duration {
fn add_assign(&mut self, rhs: Self) {
let nanos = self.nanos + rhs.nanos;
self.secs += rhs.secs + (nanos / 1_000_000_000) as u64;
self.nanos = nanos % 1_000_000_000;
}
}
impl core::ops::Add for Duration {
type Output = Self;
fn add(mut self, rhs: Self) -> Self {
self += rhs;
self
}
}
impl From<core::time::Duration> for Duration {
fn from(value: core::time::Duration) -> Self {
Self {
secs: value.as_secs(),
nanos: value.subsec_nanos(),
}
}
}
impl From<Duration> for core::time::Duration {
fn from(value: Duration) -> Self {
Self::new(value.secs, value.nanos)
}
}
/// A signed [`Duration`] represented as a single [`AtomicI64`], allowing to change its value atomically.
///
/// Its resolution is 1μs, and the maximum encodable duration is 278737 years.
#[crate::stabby]
pub struct AtomicDuration {
t: AtomicI64,
}
const SHIFT: i64 = 20;
const MASK: i64 = 0xfffff;
/// A sign to be paired with a [`Duration`].
#[crate::stabby]
#[repr(u8)]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum Sign {
#[default]
/// +
Positive,
/// -
Negative,
}
impl AtomicDuration {
const fn i64_to_duration(mut t: i64) -> (Duration, Sign) {
let sign = if t.is_negative() {
t = -t;
Sign::Negative
} else {
Sign::Positive
};
let micros = (t & MASK) as u32;
let secs = t >> SHIFT;
(Duration::new(secs as u64, micros * 1000), sign)
}
const fn duration_to_i64(t: Duration, sign: Sign) -> i64 {
let t = ((t.as_secs() as i64) << SHIFT) + (t.subsec_micros() as i64);
match sign {
Sign::Positive => t,
Sign::Negative => -t,
}
}
/// This type's time resolution.
pub const RESOLUTION: Duration = Self::i64_to_duration(1).0;
/// This type's maximum value.
pub const MAX: Duration = Self::i64_to_duration(i64::MAX).0;
/// Atomically loads the stored value, converting it to a duration-sign tuple.
///
/// The [`Ordering`] is used in a single `load` operation.
pub fn load(&self, ord: Ordering) -> (Duration, Sign) {
Self::i64_to_duration(self.t.load(ord))
}
/// Converts the duration-sign tuple into before storing it atomically.
///
/// The [`Ordering`] is used in a single `store` operation.
pub fn store(&self, duration: Duration, sign: Sign, ord: Ordering) {
self.t.store(Self::duration_to_i64(duration, sign), ord)
}
/// Perform a [`AtomicDuration::load`] and [`AtomicDuration::store`] in a single atomic operation
pub fn swap(&self, duration: Duration, sign: Sign, ord: Ordering) -> (Duration, Sign) {
Self::i64_to_duration(self.t.swap(Self::duration_to_i64(duration, sign), ord))
}
/// Construct a new [`AtomicDuration`]
pub const fn new(duration: Duration, sign: Sign) -> Self {
Self {
t: AtomicI64::new(Self::duration_to_i64(duration, sign)),
}
}
}
#[cfg(feature = "std")]
pub use impls::{AtomicInstant, Instant, SystemTime};
#[cfg(feature = "std")]
mod impls {
use super::{AtomicDuration, Duration};
use core::sync::atomic::Ordering;
use std::time::UNIX_EPOCH;
/// A stable equivalent to [`std::time::SystemTime`].
/// # Stability
/// It is always represented as a duration since [`std::time::UNIX_EPOCH`].
#[crate::stabby]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SystemTime(pub(crate) Duration);
impl SystemTime {
/// An anchor in time which can be used to create new SystemTime instances or learn about where in time a SystemTime lies.
///
/// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with respect to the system clock. Using duration_since on an existing SystemTime instance can tell how far away from this point in time a measurement lies, and using UNIX_EPOCH + duration can be used to create a SystemTime instance to represent another fixed point in time.
pub const UNIX_EPOCH: Self = SystemTime(Duration { secs: 0, nanos: 0 });
/// Measure the current [`SystemTime`].
pub fn now() -> Self {
std::time::SystemTime::now().into()
}
}
impl core::ops::AddAssign<Duration> for SystemTime {
fn add_assign(&mut self, rhs: Duration) {
self.0.add_assign(rhs)
}
}
impl core::ops::Add<Duration> for SystemTime {
type Output = Self;
fn add(mut self, rhs: Duration) -> Self {
self += rhs;
self
}
}
impl From<std::time::SystemTime> for SystemTime {
fn from(value: std::time::SystemTime) -> Self {
Self(
value
.duration_since(UNIX_EPOCH)
.unwrap_or(core::time::Duration::new(0, 0))
.into(),
)
}
}
impl From<SystemTime> for std::time::SystemTime {
fn from(value: SystemTime) -> Self {
UNIX_EPOCH + value.0.into()
}
}
/// A stable equivalent to [`std::time::Instant`].
///
/// # Stability
/// It is always represented as a duration since a mem-zeroed [`std::time::Instant`].
///
/// ## Verified platforms
/// Platforms where [`Instant`] is known to be stable accross processes:
/// - Unix systems use [`libc::CLOCK_MONOTONIC`](https://docs.rs/libc/latest/libc/constant.CLOCK_MONOTONIC.html), which is system-global.
/// - MacOS use [`libc::CLOCK_UPTIME_RAW`](https://docs.rs/libc/latest/libc/constant.CLOCK_UPTIME_RAW.html), which is system-global.
/// - Windows uses performance counters, and [states](https://learn.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps#guidance-for-acquiring-time-stamps) that said counters are consistent accross processes, except on platforms that don't provide consistent multi-core counters on pre-Vista systems
///
/// Platforms where [`Instant`] is only known to be stable within a process:
/// - None to date
///
/// Platforms where [`Instant`] is only known to be unstable accross dynamic linkage units:
/// - None to date, if such a platform is discovered and distinguishable, its support for
/// [`Instant`] will be retracted until a stable representation is found.
///
/// ## Doubts
/// While this representation should work on most platforms, it assumes that within a
/// given process, but accross dynamic linkage units, the OS will use the same clock
/// to construct [`std::time::Instant`].
///
/// While very likely to be true, this is unverified yet for niche platforms.
/// Please write an issue on [stabby's official repo](https://github.com/ZettaScaleLabs/stabby)
/// if you have proof either way for your system of choice, and it will be added
/// to this documentation.
#[crate::stabby]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Instant(pub(crate) Duration);
impl Instant {
/// The epoch of the [`Instant`] type.
pub const fn zero() -> Self {
Self(Duration { secs: 0, nanos: 0 })
}
/// Measure the current [`Instant`].
pub fn now() -> Self {
std::time::Instant::now().into()
}
}
#[rustversion::attr(since(1.75), const)]
fn instant_epoch() -> std::time::Instant {
unsafe { core::mem::MaybeUninit::zeroed().assume_init() }
}
impl core::ops::AddAssign<Duration> for Instant {
fn add_assign(&mut self, rhs: Duration) {
self.0.add_assign(rhs)
}
}
impl core::ops::Add<Duration> for Instant {
type Output = Self;
fn add(mut self, rhs: Duration) -> Self {
self += rhs;
self
}
}
impl From<std::time::Instant> for Instant {
fn from(value: std::time::Instant) -> Self {
Self(value.duration_since(instant_epoch()).into())
}
}
impl From<Instant> for std::time::Instant {
fn from(value: Instant) -> Self {
instant_epoch() + value.0.into()
}
}
/// An [`Instant`] stored as an [`AtomicDuration`] since [`Instant::zero`]
#[crate::stabby]
pub struct AtomicInstant(pub(crate) AtomicDuration);
impl AtomicInstant {
/// Measure the current time into a new [`AtomicInstant`].
pub fn now() -> Self {
Self(AtomicDuration::new(
instant_epoch().elapsed().into(),
super::Sign::Positive,
))
}
/// Construct the epoch for [`AtomicInstant`].
pub const fn epoch() -> Self {
Self(AtomicDuration::new(
Duration::new(0, 0),
super::Sign::Positive,
))
}
/// Atomically update `self` to [`Instant::now`] while returning its previous value.
pub fn update(&self, ordering: Ordering) -> Instant {
Instant(
self.0
.swap(
instant_epoch().elapsed().into(),
super::Sign::Positive,
ordering,
)
.0,
)
}
/// Atomically update `self` to `instant` while returning its previous value.
pub fn swap(&self, instant: Instant, ordering: Ordering) -> Instant {
Instant(self.0.swap(instant.0, super::Sign::Positive, ordering).0)
}
/// Atomically read `self`.
pub fn load(&self, ordering: Ordering) -> Instant {
Instant(self.0.load(ordering).0)
}
/// Atomically write `instant` to `self`.
pub fn store(&self, instant: Instant, ordering: Ordering) {
self.0.store(instant.0, super::Sign::Positive, ordering)
}
}
}