Expand description
§clock-lib
TIME READINGS FOR RUST
Monotonic and wall-clock time readings with a mockable clock for deterministic
testing. Simple Tier-1 API, zero dependencies, no unsafe.
§Two kinds of time
There are two fundamentally different kinds of time, and conflating them is a common source of bugs:
- Monotonic time (
now) never goes backwards. Use it to measure elapsed time: rate limiting, timeouts, benchmarks. Only meaningful as a delta. - Wall-clock time (
wall,unix) is calendar time. It can jump (NTP, DST, manual changes). Use it for timestamps and logging, never for measuring elapsed time.
The two are returned as distinct types — Monotonic and Wall — so the
compiler rejects any attempt to subtract one from the other. That separation
is the central design choice of the crate.
§Tier-1 API (the lazy path)
use clock_lib as clock;
let start = clock::now(); // monotonic reading
// ... do work ...
let took = clock::elapsed(start); // Duration since `start`
let secs = clock::unix(); // unix seconds (like PHP time())§Tier-2 API (the mockable clock)
The real value is deterministic time in tests. The Clock trait has two
implementations — SystemClock for production and ManualClock
for tests — so timing-driven code can be exercised without ever
calling sleep.
use clock_lib::{Clock, ManualClock, Monotonic};
use std::time::Duration;
fn expired<C: Clock>(clock: &C, stamp: Monotonic, ttl: Duration) -> bool {
clock.now().duration_since(stamp) >= ttl
}
let clock = ManualClock::new();
let stamp = clock.now();
assert!(!expired(&clock, stamp, Duration::from_secs(60)));
clock.advance(Duration::from_secs(60));
assert!(expired(&clock, stamp, Duration::from_secs(60)));§Feature flags
std(default): enables every reading API —Monotonic,Wall,Clock,SystemClock,ManualClock, and the Tier-1 free functions.
Disable default features to build for a no_std target. With std
off, only VERSION is exposed — the readings themselves require
an operating system clock and cannot be portably provided without one.
[dependencies]
clock-lib = { version = "0.5", default-features = false }§License
Dual-licensed under Apache-2.0 OR MIT.
Structs§
- Manual
Clock std - A clock under your control, for deterministic testing.
- Monotonic
std - A captured monotonic instant.
- System
Clock std - A clock backed by the operating system.
- Wall
std - A captured wall-clock instant.
Constants§
- VERSION
- Crate version string, populated by Cargo at build time.
Traits§
- Clock
std - A source of time.
Functions§
- elapsed
std - Returns the
Durationelapsed sinceearlier. - now
std - Captures the current monotonic time.
- unix
std - Returns the current Unix time in whole seconds.
- unix_ms
std - Returns the current Unix time in whole milliseconds.
- unix_ns
std - Returns the current Unix time in whole nanoseconds.
- wall
std - Captures the current wall-clock time.