Skip to main content

Crate clock_lib

Crate clock_lib 

Source
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

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 = "1.0", default-features = false }

§License

Dual-licensed under Apache-2.0 OR MIT.

Structs§

ManualClockstd
A clock under your control, for deterministic testing.
Monotonicstd
A captured monotonic instant.
SystemClockstd
A clock backed by the operating system.
Wallstd
A captured wall-clock instant.

Constants§

VERSION
Crate version string, populated by Cargo at build time.

Traits§

Clockstd
A source of time.

Functions§

elapsedstd
Returns the Duration elapsed since earlier.
nowstd
Captures the current monotonic time.
unixstd
Returns the current Unix time in whole seconds.
unix_msstd
Returns the current Unix time in whole milliseconds.
unix_nsstd
Returns the current Unix time in whole nanoseconds.
wallstd
Captures the current wall-clock time.