refactor(time): Introduce typed clock sources for compile-time safety
This change replaces runtime `ClockId` parameters with distinct types to ensure correct clock usage at compile time.
This commit is contained in:
6 files changed
+46
-26
No files matched your search
+32
-11
@@ -2,27 +2,42 @@
|
||||
//
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
use rustix::fs::Timespec;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use rustix::time::{ClockId, clock_gettime};
|
||||
|
||||
pub struct Time {
|
||||
time_s: u64,
|
||||
time_ns: u64,
|
||||
trait Clock {
|
||||
const ID: ClockId;
|
||||
}
|
||||
|
||||
impl Time {
|
||||
pub fn new(id: ClockId) -> Self {
|
||||
let time: Timespec = clock_gettime(id);
|
||||
pub enum Realtime {}
|
||||
pub enum Monotonic {}
|
||||
|
||||
impl Clock for Realtime {
|
||||
const ID: ClockId = ClockId::Realtime;
|
||||
}
|
||||
|
||||
impl Clock for Monotonic {
|
||||
const ID: ClockId = ClockId::Monotonic;
|
||||
}
|
||||
|
||||
pub struct ClockSample<C> {
|
||||
time_s: u64,
|
||||
time_ns: u64,
|
||||
_clock: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<C: Clock> ClockSample<C> {
|
||||
pub fn now() -> Self {
|
||||
let time = clock_gettime(C::ID);
|
||||
|
||||
Self {
|
||||
time_s: time.tv_sec as u64,
|
||||
time_ns: time.tv_nsec as u64,
|
||||
_clock: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_time_since_midnight(&self) -> i64 {
|
||||
(self.time_s as i64 % 86400 * 1000) + (self.time_ns as i64 / 1000000)
|
||||
}
|
||||
|
||||
pub fn secs(&self) -> u64 {
|
||||
self.time_s
|
||||
}
|
||||
@@ -43,3 +58,9 @@ impl Time {
|
||||
(self.time_s * 1000) + (self.time_ns / 1000000)
|
||||
}
|
||||
}
|
||||
|
||||
impl ClockSample<Realtime> {
|
||||
pub fn as_time_since_midnight(&self) -> i64 {
|
||||
(self.time_s as i64 % 86_400 * 1000) + self.time_ns as i64 / 1_000_000
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user