use crate::{ClockDrive, ClockError, ClockRead};
use rusty_time_core::ClockCommand;
pub struct SystemClock;
const ADJTIME_RESOLUTION_US: f64 = 1.0;
const MAX_SLEW_PPM: f64 = 5_000.0;
fn errno_detail(op: &'static str) -> ClockError {
ClockError {
op,
detail: std::io::Error::last_os_error().to_string(),
}
}
pub(crate) fn platform_capabilities() -> crate::ClockCapabilities {
crate::ClockCapabilities {
os: "macos",
arch: std::env::consts::ARCH,
can_read: true,
can_discipline: unsafe { libc::geteuid() } == 0,
discipline_requirement: "root (macOS exposes no per-binary time capability); \
run from launchd as a system daemon",
slew_resolution_ppm: Some(ADJTIME_RESOLUTION_US),
max_slew_ppm: MAX_SLEW_PPM,
batch_receive: false,
mono_resolution_ns: None,
}
}
impl ClockRead for SystemClock {
fn wall_ns(&self) -> Result<i128, ClockError> {
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
let rc = unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts) };
if rc != 0 {
return Err(errno_detail("clock_gettime(REALTIME)"));
}
Ok(ts.tv_sec as i128 * 1_000_000_000 + ts.tv_nsec as i128)
}
fn mono_s(&self) -> Result<f64, ClockError> {
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
let rc = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut ts) };
if rc != 0 {
return Err(errno_detail("clock_gettime(MONOTONIC_RAW)"));
}
Ok(ts.tv_sec as f64 + ts.tv_nsec as f64 * 1e-9)
}
}
impl SystemClock {
fn adjtime_by(&self, seconds: f64) -> Result<(), ClockError> {
let sec = seconds.trunc() as libc::time_t;
let usec = ((seconds - seconds.trunc()) * 1e6) as libc::suseconds_t;
let delta = libc::timeval {
tv_sec: sec,
tv_usec: usec,
};
let rc = unsafe { libc::adjtime(&delta, core::ptr::null_mut()) };
if rc != 0 {
return Err(errno_detail("adjtime"));
}
Ok(())
}
}
impl ClockDrive for SystemClock {
fn apply(&mut self, cmd: &ClockCommand) -> Result<(), ClockError> {
match *cmd {
ClockCommand::Step { add_seconds } => {
let now = self.wall_ns()?;
let target_ns = now + (add_seconds * 1e9) as i128;
let ts = libc::timespec {
tv_sec: (target_ns / 1_000_000_000) as libc::time_t,
tv_nsec: (target_ns % 1_000_000_000) as libc::c_long,
};
let rc = unsafe { libc::clock_settime(libc::CLOCK_REALTIME, &ts) };
if rc != 0 {
return Err(errno_detail("clock_settime"));
}
Ok(())
}
ClockCommand::Slew {
freq_ppm,
drain_offset,
drain_rate_ppm,
} => {
let amount =
crate::slew::macos_adjtime_amount(freq_ppm, drain_offset, drain_rate_ppm);
if amount.abs() < ADJTIME_RESOLUTION_US * 1e-6 {
return Ok(());
}
self.adjtime_by(amount)
}
}
}
}