use std::time::{Duration, Instant, SystemTime};
use oscall::ErrorKind;
use oscall::time::{self, Clock, Timestamp};
fn spin_until_advanced(clock: Clock) -> (Duration, Duration) {
let start = clock.now().unwrap();
let mut value = 1u64;
loop {
for i in 0..100_000u64 {
value = std::hint::black_box(value.wrapping_mul(6364136223846793005).wrapping_add(i));
}
let now = clock.now().unwrap();
assert!(now >= start);
if now > start {
return (start, now);
}
}
}
#[test]
fn timestamp_arithmetic() {
let epoch = Timestamp::UNIX_EPOCH;
assert_eq!(epoch, Timestamp::default());
let t = Timestamp {
secs: 10,
nanos: 900_000_000,
};
let later = t.checked_add(Duration::new(1, 200_000_000)).unwrap();
assert_eq!(
later,
Timestamp {
secs: 12,
nanos: 100_000_000
}
);
assert_eq!(later.checked_sub(Duration::new(1, 200_000_000)), Some(t));
assert_eq!(later.duration_since(t), Some(Duration::new(1, 200_000_000)));
assert_eq!(t.duration_since(later), None);
assert_eq!(t.duration_since(t), Some(Duration::ZERO));
assert!(t < later);
let before = epoch.checked_sub(Duration::new(1, 250_000_000)).unwrap();
assert_eq!(
before,
Timestamp {
secs: -2,
nanos: 750_000_000
}
);
assert_eq!(before.to_unix(), None);
assert_eq!(
epoch.duration_since(before),
Some(Duration::new(1, 250_000_000))
);
assert_eq!(
before.checked_add(Duration::new(1, 250_000_000)),
Some(epoch)
);
assert_eq!(
Timestamp::from_unix(Duration::new(10, 900_000_000)),
Some(t)
);
assert_eq!(t.to_unix(), Some(Duration::new(10, 900_000_000)));
let max = Timestamp {
secs: i64::MAX,
nanos: 999_999_999,
};
let min = Timestamp {
secs: i64::MIN,
nanos: 0,
};
assert_eq!(max.checked_add(Duration::from_nanos(1)), None);
assert_eq!(max.checked_add(Duration::ZERO), Some(max));
assert_eq!(min.checked_sub(Duration::from_nanos(1)), None);
assert_eq!(epoch.checked_add(Duration::MAX), None);
assert_eq!(epoch.checked_sub(Duration::MAX), None);
assert_eq!(Timestamp::from_unix(Duration::MAX), None);
assert_eq!(
max.duration_since(min),
Some(Duration::new(u64::MAX, 999_999_999))
);
assert_eq!(min.duration_since(max), None);
}
#[test]
fn timestamp_out_of_range() {
let t = Timestamp {
secs: 10,
nanos: 900_000_000,
};
for nanos in [1_000_000_000, 1_500_000_000, u32::MAX - 1, u32::MAX] {
let invalid = Timestamp { secs: 10, nanos };
for duration in [
Duration::ZERO,
Duration::from_nanos(1),
Duration::new(1, 999_999_999),
Duration::MAX,
] {
assert_eq!(invalid.checked_add(duration), None);
assert_eq!(invalid.checked_sub(duration), None);
}
assert_eq!(invalid.duration_since(t), None);
assert_eq!(t.duration_since(invalid), None);
assert_eq!(invalid.duration_since(invalid), None);
assert_eq!(invalid.duration_since(Timestamp::UNIX_EPOCH), None);
assert_eq!(invalid.to_unix(), None);
#[cfg(feature = "std")]
assert_eq!(
SystemTime::try_from(invalid).unwrap_err(),
ErrorKind::InvalidInput
);
}
}
#[cfg(feature = "std")]
#[test]
fn timestamp_system_time() {
let epoch = SystemTime::UNIX_EPOCH;
assert_eq!(Timestamp::from(epoch), Timestamp::UNIX_EPOCH);
assert_eq!(SystemTime::try_from(Timestamp::UNIX_EPOCH).unwrap(), epoch);
let after = epoch + Duration::new(1_700_000_000, 123_456_700);
let t = Timestamp::from(after);
assert_eq!(
t,
Timestamp {
secs: 1_700_000_000,
nanos: 123_456_700
}
);
assert_eq!(SystemTime::try_from(t).unwrap(), after);
let t = Timestamp {
secs: -2,
nanos: 750_000_000,
};
match epoch.checked_sub(Duration::new(1, 250_000_000)) {
Some(before) => {
assert_eq!(Timestamp::from(before), t);
assert_eq!(SystemTime::try_from(t).unwrap(), before);
}
None => assert_eq!(
SystemTime::try_from(t).unwrap_err(),
ErrorKind::InvalidInput
),
}
let now = SystemTime::now();
assert_eq!(
Timestamp::from(now).to_unix(),
Some(now.duration_since(epoch).unwrap())
);
let invalid = Timestamp {
secs: 0,
nanos: 1_000_000_000,
};
assert_eq!(
SystemTime::try_from(invalid).unwrap_err(),
ErrorKind::InvalidInput
);
}
#[test]
fn now_matches_std() {
let before = SystemTime::now();
let now = time::now().unwrap();
let after = SystemTime::now();
assert!(now.nanos < 1_000_000_000);
let now = SystemTime::UNIX_EPOCH + now.to_unix().unwrap();
let slack = Duration::from_secs(2);
assert!(now + slack >= before, "{now:?} < {before:?}");
assert!(now <= after + slack, "{now:?} > {after:?}");
}
#[test]
fn monotonic_clocks() {
for clock in [Clock::Monotonic, Clock::Boottime] {
if cfg!(target_family = "wasm") && clock == Clock::Boottime {
assert_eq!(clock.now().unwrap_err(), ErrorKind::Unsupported);
assert_eq!(clock.resolution().unwrap_err(), ErrorKind::Unsupported);
continue;
}
let mut last = clock.now().unwrap();
for _ in 0..1000 {
let now = clock.now().unwrap();
assert!(now >= last, "{clock:?} went backwards");
last = now;
}
let pause = Duration::from_millis(20);
let std_start = Instant::now();
let start = clock.now().unwrap();
std::thread::sleep(pause);
let elapsed = clock.now().unwrap() - start;
let std_elapsed = std_start.elapsed();
assert!(
elapsed + Duration::from_millis(1) >= pause,
"{clock:?}: {elapsed:?}"
);
assert!(
elapsed <= std_elapsed + Duration::from_millis(50),
"{clock:?}: {elapsed:?} > {std_elapsed:?}"
);
}
}
#[test]
fn clocks_never_go_backwards() {
for clock in [Clock::Monotonic, Clock::Boottime] {
if cfg!(target_family = "wasm") && clock == Clock::Boottime {
continue;
}
let mut last = clock.now().unwrap();
for _ in 0..200_000 {
let now = clock.now().unwrap();
assert!(
now >= last,
"{clock:?} went backwards: {last:?} then {now:?}"
);
last = now;
}
}
for clock in [Clock::ProcessCpu, Clock::ThreadCpu] {
if cfg!(target_os = "wasi") && clock.now().is_err() {
continue;
}
let mut last = clock.now().unwrap();
for _ in 0..2_000 {
let now = clock.now().unwrap();
assert!(
now >= last,
"{clock:?} went backwards: {last:?} then {now:?}"
);
last = now;
}
}
}
#[test]
fn monotonic_matches_boottime_rate() {
if cfg!(target_family = "wasm") {
return; }
let monotonic = Clock::Monotonic.now().unwrap();
let boottime = Clock::Boottime.now().unwrap();
assert!(
boottime + Duration::from_millis(100) >= monotonic,
"{boottime:?} < {monotonic:?}"
);
}
#[test]
fn cpu_clocks() {
for clock in [Clock::ProcessCpu, Clock::ThreadCpu] {
if cfg!(target_os = "wasi") && clock.now().is_err() {
continue;
}
let wall = Instant::now();
let (start, end) = spin_until_advanced(clock);
let wall = wall.elapsed();
assert!(end > start);
if clock == Clock::ThreadCpu {
assert!(
end - start <= wall + Duration::from_millis(100),
"{:?} > {wall:?}",
end - start
);
}
}
}
#[test]
fn cpu_clock_does_not_count_sleep() {
let clock = Clock::ThreadCpu;
if cfg!(target_os = "wasi") && clock.now().is_err() {
return; }
let start = clock.now().unwrap();
time::sleep(Duration::from_millis(300)).unwrap();
let used = clock.now().unwrap() - start;
assert!(used < Duration::from_millis(250), "{used:?}");
}
#[test]
fn thread_cpu_is_per_thread() {
if cfg!(target_os = "wasi") {
return; }
let (_, mine) = spin_until_advanced(Clock::ThreadCpu);
let mut value = 0u64;
let spin = Instant::now();
while spin.elapsed() < Duration::from_millis(50) {
value = std::hint::black_box(value.wrapping_add(1));
}
let mine = Clock::ThreadCpu.now().unwrap().max(mine);
let other = std::thread::spawn(|| Clock::ThreadCpu.now().unwrap())
.join()
.unwrap();
assert!(other < mine, "{other:?} >= {mine:?}");
let process = Clock::ProcessCpu.now().unwrap();
assert!(
process + Duration::from_millis(50) >= mine,
"{process:?} < {mine:?}"
);
}
#[test]
fn resolution() {
for clock in [
Clock::Monotonic,
Clock::Boottime,
Clock::ProcessCpu,
Clock::ThreadCpu,
] {
if cfg!(target_os = "wasi") && clock != Clock::Monotonic && clock.resolution().is_err() {
continue;
}
let resolution = clock.resolution().unwrap();
assert!(!resolution.is_zero(), "{clock:?}");
assert!(resolution <= Duration::from_millis(100), "{clock:?}");
}
}
#[test]
fn sleep() {
time::sleep(Duration::ZERO).unwrap();
for pause in [
Duration::from_nanos(1),
Duration::from_micros(1500),
Duration::from_millis(30),
Duration::from_millis(120),
] {
let std_start = Instant::now();
let start = Clock::Monotonic.now().unwrap();
time::sleep(pause).unwrap();
let elapsed = Clock::Monotonic.now().unwrap() - start;
let std_elapsed = std_start.elapsed();
assert!(elapsed >= pause, "{elapsed:?} < {pause:?}");
assert!(
std_elapsed + Duration::from_micros(100) >= pause,
"{std_elapsed:?} < {pause:?}"
);
}
}
#[test]
fn sleep_until() {
time::sleep_until(Duration::ZERO).unwrap();
let now = Clock::Monotonic.now().unwrap();
time::sleep_until(now).unwrap();
let pause = Duration::from_millis(40);
let std_start = Instant::now();
let deadline = Clock::Monotonic.now().unwrap() + pause;
time::sleep_until(deadline).unwrap();
assert!(Clock::Monotonic.now().unwrap() >= deadline);
assert!(std_start.elapsed() + Duration::from_micros(100) >= pause);
time::sleep_until(deadline).unwrap();
}
#[cfg(not(target_os = "wasi"))]
#[test]
fn huge_sleeps() {
let (sender, receiver) = std::sync::mpsc::channel();
let durations = [
Duration::MAX,
Duration::from_secs(u64::MAX),
Duration::from_secs(i64::MAX as u64),
Duration::from_nanos(u64::MAX),
Duration::from_nanos(i64::MAX as u64),
Duration::from_secs(u32::MAX as u64 + 1),
];
for duration in durations {
for until in [false, true] {
let sender = sender.clone();
std::thread::spawn(move || {
let result = if until {
time::sleep_until(duration)
} else {
time::sleep(duration)
};
let _ = sender.send((duration, until, result.map_err(|e| e.raw_os_error())));
});
}
}
drop(sender);
match receiver.recv_timeout(Duration::from_millis(500)) {
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
woke => panic!("a sleep is over: {woke:?}"),
}
}