sans-io-time 0.2.0

Time structures for the sans-io pattern
Documentation
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// Copyright (C) 2025 Matthew Waters <matthew@centricular.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![no_std]
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]

//! # sans-io-time
//!
//! Represent time as an abstract absolute value based on an arbitrary start point in a
//! (user-provided) timeline.
//!
//! ## Why?
//!
//! 1. `no_std` environments may require an implementation of `Instant` and may require
//!    leaving the implementation details to the implementor.
//! 2. Network protocols may require that time continues during suspend of the OS
//!    which is not something that is guaranteed by `std::time::Instant`.
//! 3. Other uses of `std::time::Instant` should not count time during suspend e.g.
//!    CPU process time, or process uptime.
//!
//! The `Instant`  type provided by this crate satisfies all of these constraints by
//! only specifying the carriage of data. It does not specify how the current time
//! is acquired or whether time continues during suspend. Both of these questions
//! are required to be answered (or left unspecified) by the caller by either using
//! `std::time::Instant` or `std::time::SystemTime` (with the "std" feature), or
//! converting from another source of time like
//! [boot-time](https://crates.io/crates/boot-time).
//!
//! In a sans-IO library, the decision on the exact clock source can be decided by the
//! user of the library rather than specifying a particular `Instant` implementation.
//!
//! ## Features
//! - "std" (enabled by default) enables conversion from `std::time::Instant` and
//!   `std::time::SystemTime` into an [`Instant`].

#[cfg(feature = "std")]
extern crate std;

use core::time::Duration;

/// An absolute point in time.
///
/// An [`Instant`] is a wrapper around a signed integer that holds the number of nanoseconds since
/// an arbitrary point in time, e.g. system startup.
///
/// - A value of `0` is arbitrary.
/// - Values < 0 indicate a time before the start point.
#[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct Instant {
    nanos: i64,
}

impl Instant {
    /// The zero [`Instant`].
    ///
    /// An arbitrary point on the absolute timescale.
    pub const ZERO: Instant = Instant { nanos: 0 };

    /// Construct an [`Instant`] from a number of nanoseconds.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sans_io_time::Instant;
    /// let instant = Instant::from_nanos(1_234_567_890);
    /// assert_eq!(instant.as_nanos(), 1_234_567_890);
    /// ```
    pub fn from_nanos(nanos: i64) -> Self {
        Self { nanos }
    }

    /// The number of nanoseconds that have passed since the `ZERO` point.
    pub const fn as_nanos(&self) -> i64 {
        self.nanos
    }

    /// The number of whole seconds since the `ZERO` point.
    pub const fn secs(&self) -> i64 {
        self.nanos / 1_000_000_000
    }

    /// The number of fractional nanoseconds since the `ZERO` point.
    pub const fn subsec_nanos(&self) -> i64 {
        self.nanos % 1_000_000_000
    }

    /// The amount of time elapsed since an earlier [`Instant`], or `0`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sans_io_time::Instant;
    /// # use core::time::Duration;
    /// let earlier = Instant::from_nanos(1_234_567_890);
    /// let later = Instant::from_nanos(2_234_567_890);
    /// assert_eq!(later.duration_since(earlier), Duration::from_nanos(1_000_000_000));
    /// assert_eq!(earlier.duration_since(later), Duration::ZERO);
    /// assert_eq!(earlier.duration_since(earlier), Duration::ZERO);
    /// ```
    pub fn duration_since(&self, earlier: Instant) -> Duration {
        self.saturating_duration_since(earlier)
    }

    /// The amount of time elapsed since an earlier [`Instant`], or `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sans_io_time::Instant;
    /// # use core::time::Duration;
    /// let earlier = Instant::from_nanos(1_234_567_890);
    /// let later = Instant::from_nanos(2_234_567_890);
    /// assert_eq!(later.checked_duration_since(earlier), Some(Duration::from_nanos(1_000_000_000)));
    /// assert_eq!(earlier.checked_duration_since(later), None);
    /// assert_eq!(earlier.checked_duration_since(earlier), Some(Duration::ZERO));
    /// ```
    pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
        self.nanos.checked_sub(earlier.nanos).and_then(|nanos| {
            if nanos < 0 {
                None
            } else {
                Some(Duration::from_nanos(nanos as u64))
            }
        })
    }

    /// The amount of time elapsed since an earlier [`Instant`], or `0`.
    pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
        self.checked_duration_since(earlier)
            .unwrap_or(Duration::ZERO)
    }

    /// Returns the result of `self + duration` if the result can be represented by the underlying
    /// data structure, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sans_io_time::Instant;
    /// # use core::time::Duration;
    /// let instant = Instant::from_nanos(1_234_567_890);
    /// assert_eq!(instant.checked_add(Duration::from_secs(1)), Some(Instant::from_nanos(2_234_567_890)));
    /// assert_eq!(instant.checked_add(Duration::ZERO), Some(instant));
    /// ```
    pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
        let dur_nanos: i64 = duration.as_nanos().try_into().ok()?;
        let nanos = self.nanos.checked_add(dur_nanos)?;
        Some(Self { nanos })
    }

    /// Returns the result of `self - duration` if the result can be represented by the underlying
    /// data structure, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sans_io_time::Instant;
    /// # use core::time::Duration;
    /// let instant = Instant::from_nanos(1_234_567_890);
    /// assert_eq!(instant.checked_sub(Duration::from_secs(1)), Some(Instant::from_nanos(234_567_890)));
    /// assert_eq!(instant.checked_sub(Duration::from_secs(2)), Some(Instant::from_nanos(-765_432_110)));
    /// assert_eq!(instant.checked_sub(Duration::ZERO), Some(instant));
    /// ```
    pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
        let dur_nanos: i64 = duration.as_nanos().try_into().ok()?;
        let nanos = self.nanos.checked_sub(dur_nanos)?;
        Some(Self { nanos })
    }

    /// Construct an [`Instant`] from a `std::time::Instant` based on its the elapsed time.
    ///
    /// Can be used if you have a base `std::time::Instant` where you can create [`Instant`]s as
    /// needed.
    ///
    /// In this usage, the base `std::time::Instant` is mapped to `Instant::ZERO` and [`Instant`]
    /// values represent the distance from the base `std::time::Instant`.
    ///
    /// # Example
    ///
    /// ```
    /// # use sans_io_time::Instant;
    /// # use core::time::Duration;
    /// let std_instant = std::time::Instant::now();
    /// std::thread::sleep(Duration::from_secs(1));
    /// assert!(Instant::from_std(std_instant) >= Instant::from_nanos(1_000_000_000));
    /// ```
    #[cfg(feature = "std")]
    pub fn from_std(instant: ::std::time::Instant) -> Self {
        let elapsed = instant.elapsed();
        Self {
            nanos: elapsed
                .as_nanos()
                .try_into()
                .expect("Elapsed time too large to fit into Instant"),
        }
    }

    /// Construct an [`Instant`] from a `std::time::SystemTime` based on its the elapsed time.
    ///
    /// Can be used if you have a base `std::time::SystemTime` where you can create [`Instant`]s as
    /// needed.
    ///
    /// In this usage, the base `std::time::SystemTime` is mapped to `Instant::ZERO` and [`Instant`]
    /// values represent the distance from the base `std::time::SystemTime`.
    ///
    /// # Example
    ///
    /// ```
    /// # use sans_io_time::Instant;
    /// # use core::time::Duration;
    /// let sys_time = std::time::SystemTime::now();
    /// std::thread::sleep(Duration::from_secs(1));
    /// assert!(Instant::from_system_elapsed(sys_time).unwrap() >= Instant::from_nanos(1_000_000_000));
    /// ```
    #[cfg(feature = "std")]
    pub fn from_system_elapsed(
        sys_time: ::std::time::SystemTime,
    ) -> Result<Self, std::time::SystemTimeError> {
        let dur = sys_time.elapsed()?;
        Ok(Self {
            nanos: dur
                .as_nanos()
                .try_into()
                .expect("Elapsed time too large to fit into Instant"),
        })
    }

    /// Construct an [`Instant`] from a `std::time::SystemTime` based on the distance from the unix
    /// epoch.
    ///
    /// In this usage, the base `std::time::UNIX_EPOCH` is mapped to `Instant::ZERO` and [`Instant`]
    /// values represent the distance from the base `std::time::UNIX_EPOCH`.
    ///
    /// # Example
    ///
    /// ```
    /// # use sans_io_time::Instant;
    /// # use core::time::Duration;
    /// let sys_time = std::time::SystemTime::now();
    /// assert!(Instant::from_system_unix_epoch(sys_time) >= Instant::from_nanos(0));
    /// ```
    #[cfg(feature = "std")]
    pub fn from_system_unix_epoch(sys_time: ::std::time::SystemTime) -> Self {
        let dur = sys_time
            .duration_since(::std::time::UNIX_EPOCH)
            .expect("start time must not be before the unix epoch");
        Self {
            nanos: dur
                .as_nanos()
                .try_into()
                .expect("Elapsed time too large to fit into Instant"),
        }
    }

    /// Convert this [`Instant`] to a `std::time::Instant` using a base instant.
    ///
    /// This function takes a base `std::time::Instant` and adds the duration represented
    /// by this [`Instant`] to create a corresponding `std::time::Instant`.
    ///
    /// In this usage, the base `std::time::Instant` is mapped to `Instant::ZERO` and [`Instant`]
    /// values represent the distance from the base `std::time::Instant`.
    ///
    /// # Example
    ///
    /// ```
    /// # use sans_io_time::Instant;
    /// # use core::time::Duration;
    /// let base = std::time::Instant::now();
    /// let instant = Instant::from_nanos(1_000_000_000); // 1 second
    /// let std_instant = instant.to_std(base);
    ///
    /// // The resulting std_instant should be 1 second after base
    /// assert!(std_instant.duration_since(base) == Duration::from_secs(1));
    /// ```
    #[cfg(feature = "std")]
    pub fn to_std(&self, base_instant: ::std::time::Instant) -> ::std::time::Instant {
        let duration_since = ::core::time::Duration::from_nanos(
            self.nanos
                .try_into()
                .expect("Elapsed time too large to fit into Duration"),
        );
        base_instant + duration_since
    }

    /// Convert this [`Instant`] to a `std::time::SystemTime` using a base system time.
    ///
    /// This function takes a base `std::time::SystemTime` and adds the duration represented
    /// by this [`Instant`] to create a corresponding `std::time::SystemTime`.
    ///
    /// If the [`Instant`] was created with [`Instant::from_system_unix_epoch`] then the base
    /// `std::time::SystemTime` should be `std::time::UNIX_EPOCH`. Otherwise, the base
    /// `std::time::SystemTime` should be the same value passed in to
    /// [`Instant::from_system_elapsed`].
    ///
    /// # Example
    ///
    /// ```
    /// # use sans_io_time::Instant;
    /// # use core::time::Duration;
    /// let base = std::time::SystemTime::now();
    /// let instant = Instant::from_nanos(1_000_000_000); // 1 second
    /// let sys_time = instant.to_system(base);
    ///
    /// // The resulting sys_time should be 1 second after base
    /// assert!(sys_time.duration_since(base).unwrap() == Duration::from_secs(1));
    /// ```
    #[cfg(feature = "std")]
    pub fn to_system(&self, base_system_time: ::std::time::SystemTime) -> ::std::time::SystemTime {
        let duration_since = ::core::time::Duration::from_nanos(
            self.nanos
                .try_into()
                .expect("Elapsed time too large to fit into Duration"),
        );
        base_system_time + duration_since
    }
}

impl core::fmt::Display for Instant {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let secs = self.secs();
        let nanos = self.subsec_nanos();
        if secs != 0 {
            write!(f, "{}", secs)?;
            if nanos != 0 {
                write!(f, ".{:0>9}", nanos.abs())?;
            }
            write!(f, "s")
        } else if nanos != 0 {
            if nanos < 0 {
                write!(f, "-")?;
            }
            let millis = nanos.abs() / 1_000_000;
            let millis_rem = nanos.abs() % 1_000_000;
            write!(f, "{}.{:0>6}ms", millis, millis_rem)
        } else {
            write!(f, "0s")
        }
    }
}

impl core::ops::Add<Duration> for Instant {
    type Output = Instant;
    fn add(self, rhs: Duration) -> Self::Output {
        self.checked_add(rhs)
            .expect("Duration too large to fit into Instant")
    }
}

impl core::ops::AddAssign<Duration> for Instant {
    fn add_assign(&mut self, rhs: Duration) {
        *self = self
            .checked_add(rhs)
            .expect("Duration too large to fit into Instant");
    }
}

impl core::ops::Sub<Duration> for Instant {
    type Output = Instant;
    fn sub(self, rhs: Duration) -> Self::Output {
        self.checked_sub(rhs)
            .expect("Duration too large to fit into Instant")
    }
}

impl core::ops::SubAssign<Duration> for Instant {
    fn sub_assign(&mut self, rhs: Duration) {
        *self = self
            .checked_sub(rhs)
            .expect("Duration too large to fit into Instant");
    }
}

impl core::ops::Sub<Instant> for Instant {
    type Output = Duration;
    fn sub(self, rhs: Instant) -> Self::Output {
        self.saturating_duration_since(rhs)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    extern crate alloc;

    #[test]
    fn add() {
        let base = Instant::from_nanos(1_222_333_444);
        assert_eq!(
            base + Duration::from_secs(1),
            Instant::from_nanos(2_222_333_444)
        );
        let mut new = base;
        new += Duration::from_secs(1);
        assert_eq!(new, Instant::from_nanos(2_222_333_444));
    }

    #[test]
    fn sub_duration() {
        let base = Instant::from_nanos(1_222_333_444);
        assert_eq!(
            base - Duration::from_secs(1),
            Instant::from_nanos(222_333_444)
        );
        let mut new = base;
        new -= Duration::from_secs(1);
        assert_eq!(new, Instant::from_nanos(222_333_444));
    }

    #[test]
    fn sub_instant() {
        let earlier = Instant::from_nanos(1_222_333_444);
        let later = Instant::from_nanos(2_333_444_555);
        assert_eq!(later - earlier, Duration::from_nanos(1_111_111_111));
        assert_eq!(earlier - later, Duration::ZERO);
        assert_eq!(earlier - earlier, Duration::ZERO);
    }

    #[test]
    fn display() {
        assert_eq!(&alloc::format!("{}", Instant::ZERO), "0s");
        assert_eq!(&alloc::format!("{}", Instant::from_nanos(1)), "0.000001ms");
        assert_eq!(
            &alloc::format!("{}", Instant::from_nanos(-1)),
            "-0.000001ms"
        );
        assert_eq!(
            &alloc::format!("{}", Instant::from_nanos(1_000_000_000)),
            "1s"
        );
        assert_eq!(
            &alloc::format!("{}", Instant::from_nanos(1_000_000_001)),
            "1.000000001s"
        );
        assert_eq!(
            &alloc::format!("{}", Instant::from_nanos(1_100_000_000)),
            "1.100000000s"
        );
        assert_eq!(
            &alloc::format!("{}", Instant::from_nanos(-1_000_000_000)),
            "-1s"
        );
        assert_eq!(
            &alloc::format!("{}", Instant::from_nanos(-1_000_000_001)),
            "-1.000000001s"
        );
        assert_eq!(
            &alloc::format!("{}", Instant::from_nanos(-1_100_000_000)),
            "-1.100000000s"
        );
    }
}