clock-lib 0.2.1

Monotonic and wall-clock time readings for Rust, with a mockable clock for deterministic testing. Simple Tier-1 API, zero dependencies, no unsafe.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
<h1 align="center">
    <img width="99" alt="Rust logo" src="https://raw.githubusercontent.com/jamesgober/rust-collection/72baabd71f00e14aa9184efcb16fa3deddda3a0a/assets/rust-logo.svg">
    <br><b>clock-lib</b><br>
    <sub><sup>API REFERENCE</sup></sub>
</h1>
<div align="center">
    <sup>
        <a href="../README.md" title="Project Home"><b>HOME</b></a>
        <span>&nbsp;&mdash;&nbsp;</span>
        <a href="./GUIDELINES.md" title="Developer Guidelines"><b>GUIDELINES</b></a>
        <span>&nbsp;&mdash;&nbsp;</span>
        <span>API</span>
    </sup>
</div>
<br>

> **Status:** This reference tracks the public surface of `clock-lib` **0.2.1**. Every example is verified against the current codebase.

`clock-lib` exposes two complementary readings &mdash; **monotonic** (for measuring elapsed time) and **wall-clock** (for timestamps) &mdash; behind a one-line Tier-1 API. The two are distinct types and cannot be mixed: the compiler rejects any attempt to subtract a wall-clock reading from a monotonic one, eliminating an entire class of subtle timing bugs.

## Table of Contents

- [Installation]#installation
- [Quick Start]#quick-start
- [Tier-1 Functions]#tier-1-functions
  - [`now`]#now
  - [`elapsed`]#elapsed
  - [`wall`]#wall
  - [`unix`]#unix
  - [`unix_ms`]#unix_ms
  - [`unix_ns`]#unix_ns
- [Types]#types
  - [`Monotonic`]#monotonic
    - [`Monotonic::now`]#monotonicnow
    - [`Monotonic::elapsed`]#monotonicelapsed
    - [`Monotonic::duration_since`]#monotonicduration_since
    - [`Monotonic::checked_duration_since`]#monotonicchecked_duration_since
    - [`Monotonic::saturating_duration_since`]#monotonicsaturating_duration_since
  - [`Wall`]#wall-1
    - [`Wall::now`]#wallnow
    - [`Wall::unix_seconds`]#wallunix_seconds
    - [`Wall::unix_millis`]#wallunix_millis
    - [`Wall::unix_nanos`]#wallunix_nanos
- [Constants]#constants
  - [`VERSION`]#version

<br>

## Installation

Add to `Cargo.toml`:

```toml
[dependencies]
clock-lib = "0.2"
```

`clock-lib` has zero runtime dependencies, supports `no_std` builds via `default-features = false`, and contains no `unsafe` code.

<br>

## Quick Start

```rust
use clock_lib as clock;

// Measure elapsed time (monotonic — safe even across NTP corrections).
let start = clock::now();
// ... do work ...
let took = clock::elapsed(start);

// Stamp an event (wall-clock).
let seconds = clock::unix();
let millis = clock::unix_ms();
let nanos = clock::unix_ns();
# let _ = (took, seconds, millis, nanos);
```

<br>

## Tier-1 Functions

The Tier-1 surface is the one-line entry point per common operation. It is the recommended path unless you have a reason to hold the typed values directly.

### `now`

```rust
pub fn now() -> Monotonic
```

Captures the current monotonic time from the operating system. Pair with [`elapsed`](#elapsed) to measure how long an operation took.

**Returns:** a [`Monotonic`](#monotonic) reading suitable for delta math against another `Monotonic` from the same process.

**Example &mdash; measuring a block of work:**

```rust
use clock_lib as clock;

let start = clock::now();
// ... do work ...
let took = clock::elapsed(start);
println!("operation took {took:?}");
```

**Example &mdash; tracking multiple checkpoints:**

```rust
use clock_lib as clock;

let t0 = clock::now();
let parsed = parse_input();
let t1 = clock::now();
let processed = process(parsed);
let t2 = clock::now();

let parse_time = t1.duration_since(t0);
let process_time = t2.duration_since(t1);
# fn parse_input() {}
# fn process(_: ()) {}
# let _ = (parse_time, process_time);
```

<br>

### `elapsed`

```rust
pub fn elapsed(earlier: Monotonic) -> Duration
```

Returns the [`Duration`](https://doc.rust-lang.org/core/time/struct.Duration.html) between `earlier` and the current monotonic time. Equivalent to `Monotonic::now().duration_since(earlier)`.

**Parameters:**

| Name | Type | Description |
| --- | --- | --- |
| `earlier` | [`Monotonic`]#monotonic | The reading captured at the start of the interval. |

**Returns:** the time elapsed since `earlier`, as a `Duration`.

**Example &mdash; rate limiting:**

```rust
use clock_lib as clock;
use std::time::Duration;

let last_call = clock::now();
// ... later ...
if clock::elapsed(last_call) < Duration::from_secs(1) {
    // too soon — skip
}
```

<br>

### `wall`

```rust
pub fn wall() -> Wall
```

Captures the current wall-clock time from the operating system's real-time clock. Use this for timestamps. Do **not** use it to measure elapsed time &mdash; wall-clock readings can jump forwards or backwards (NTP, DST, manual changes).

**Returns:** a [`Wall`](#wall-1) reading that can be converted to Unix time at second, millisecond, or nanosecond resolution.

**Example:**

```rust
use clock_lib as clock;

let stamp = clock::wall();
let event_seconds = stamp.unix_seconds();
let event_millis = stamp.unix_millis();
# let _ = (event_seconds, event_millis);
```

<br>

### `unix`

```rust
pub fn unix() -> u64
```

Returns the current Unix time in whole seconds. Equivalent in spirit to C's `time(NULL)` or PHP's `time()`.

**Returns:** seconds elapsed since `1970-01-01 00:00:00 UTC`, as `u64`. Returns `0` if the system clock is set to a moment before the Unix epoch.

**Example:**

```rust
use clock_lib as clock;

let now = clock::unix();
println!("event at {now}");
```

<br>

### `unix_ms`

```rust
pub fn unix_ms() -> u128
```

Returns the current Unix time in whole milliseconds.

**Returns:** milliseconds elapsed since `1970-01-01 00:00:00 UTC`, as `u128`. Returns `0` if the system clock is set to a moment before the Unix epoch.

**Example:**

```rust
use clock_lib as clock;

let event_id = format!("evt-{}", clock::unix_ms());
# let _ = event_id;
```

<br>

### `unix_ns`

```rust
pub fn unix_ns() -> u128
```

Returns the current Unix time in whole nanoseconds.

**Returns:** nanoseconds elapsed since `1970-01-01 00:00:00 UTC`, as `u128`. Returns `0` if the system clock is set to a moment before the Unix epoch.

**Example:**

```rust
use clock_lib as clock;

let high_res_stamp = clock::unix_ns();
# let _ = high_res_stamp;
```

<br>

## Types

### `Monotonic`

```rust
pub struct Monotonic(/* opaque */);
```

A captured monotonic instant. `Monotonic` wraps a single sample of the operating system's monotonic clock. Monotonic time never goes backwards, which makes it the correct choice for measuring elapsed time: rate limiting, timeouts, benchmarks, retry backoff.

The absolute value of a `Monotonic` reading carries no calendar meaning &mdash; it is only useful as a delta against another `Monotonic` from the same process. For calendar timestamps, use [`Wall`](#wall-1) instead.

**Derived traits:** `Debug`, `Copy`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Hash`.

**Type-level separation.** `Monotonic` and [`Wall`](#wall-1) are deliberately distinct types with no cross-type arithmetic. The compiler will refuse to mix them &mdash; that is the central design choice of this crate, and it eliminates a class of bugs at the source.

<br>

#### `Monotonic::now`

```rust
pub fn now() -> Monotonic
```

Captures the current monotonic time from the operating system. The crate-level [`now`](#now) function is a one-line shortcut for the same thing.

**Example:**

```rust
use clock_lib::Monotonic;

let t = Monotonic::now();
# let _ = t;
```

<br>

#### `Monotonic::elapsed`

```rust
pub fn elapsed(self) -> Duration
```

Returns the [`Duration`](https://doc.rust-lang.org/core/time/struct.Duration.html) elapsed since this reading was captured. Equivalent to `Monotonic::now().duration_since(self)`.

**Example:**

```rust
use clock_lib::Monotonic;

let t = Monotonic::now();
// ... work ...
let took = t.elapsed();
# let _ = took;
```

<br>

#### `Monotonic::duration_since`

```rust
pub fn duration_since(self, earlier: Monotonic) -> Duration
```

Returns the `Duration` between two readings.

**Parameters:**

| Name | Type | Description |
| --- | --- | --- |
| `earlier` | [`Monotonic`]#monotonic | A reading that must be at or before `self`. |

**Panics:** if `earlier` is later than `self`. Prefer [`checked_duration_since`](#monotonicchecked_duration_since) or [`saturating_duration_since`](#monotonicsaturating_duration_since) when the ordering is not guaranteed by construction.

**Example:**

```rust
use clock_lib::Monotonic;

let earlier = Monotonic::now();
let later = Monotonic::now();
let delta = later.duration_since(earlier);
# let _ = delta;
```

<br>

#### `Monotonic::checked_duration_since`

```rust
pub fn checked_duration_since(self, earlier: Monotonic) -> Option<Duration>
```

The non-panicking counterpart to [`duration_since`](#monotonicduration_since). Returns `Some(duration)` if `self >= earlier`, otherwise `None`.

**Example &mdash; tolerating out-of-order timestamps:**

```rust
use clock_lib::Monotonic;

let a = Monotonic::now();
let b = Monotonic::now();
match b.checked_duration_since(a) {
    Some(delta) => println!("forward {delta:?}"),
    None => println!("a was after b — skipping"),
}
```

<br>

#### `Monotonic::saturating_duration_since`

```rust
pub fn saturating_duration_since(self, earlier: Monotonic) -> Duration
```

Returns the duration since `earlier`, saturating at zero when `earlier` is later than `self`. Never panics.

**Example:**

```rust
use clock_lib::Monotonic;
use std::time::Duration;

let a = Monotonic::now();
let b = Monotonic::now();
let delta = a.saturating_duration_since(b);
assert!(delta == Duration::ZERO || delta > Duration::ZERO);
```

<br>

### `Wall`

```rust
pub struct Wall(/* opaque */);
```

A captured wall-clock instant. `Wall` wraps a single sample of the operating system's real-time clock. Convert it to Unix time with [`unix_seconds`](#wallunix_seconds), [`unix_millis`](#wallunix_millis), or [`unix_nanos`](#wallunix_nanos).

`Wall` is the right tool for timestamps in logs, audit records, and anything that needs to line up with what a wristwatch shows. It is the wrong tool for measuring elapsed time &mdash; wall-clock readings can jump. For that, use [`Monotonic`](#monotonic).

**Derived traits:** `Debug`, `Copy`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Hash`.

**Pre-epoch behavior.** If the system clock is set to a moment before `1970-01-01 00:00:00 UTC`, all `unix_*` accessors saturate to `0`. They never panic and never silently wrap.

<br>

#### `Wall::now`

```rust
pub fn now() -> Wall
```

Captures the current wall-clock time from the operating system. The crate-level [`wall`](#wall) function is a one-line shortcut for the same thing.

**Example:**

```rust
use clock_lib::Wall;

let stamp = Wall::now();
# let _ = stamp;
```

<br>

#### `Wall::unix_seconds`

```rust
pub fn unix_seconds(self) -> u64
```

Returns Unix time in whole seconds.

**Returns:** seconds since `1970-01-01 00:00:00 UTC`. Returns `0` for pre-epoch system clocks. The `u64` range is sufficient to represent any plausible wall-clock value through year 584,942,417,355 &mdash; this accessor cannot overflow.

**Example:**

```rust
use clock_lib::Wall;

let secs = Wall::now().unix_seconds();
assert!(secs > 0);
```

<br>

#### `Wall::unix_millis`

```rust
pub fn unix_millis(self) -> u128
```

Returns Unix time in whole milliseconds.

**Returns:** milliseconds since `1970-01-01 00:00:00 UTC`. Returns `0` for pre-epoch system clocks. The `u128` return type cannot overflow for any representable `SystemTime`.

**Example:**

```rust
use clock_lib::Wall;

let millis = Wall::now().unix_millis();
assert!(millis > 0);
```

<br>

#### `Wall::unix_nanos`

```rust
pub fn unix_nanos(self) -> u128
```

Returns Unix time in whole nanoseconds.

**Returns:** nanoseconds since `1970-01-01 00:00:00 UTC`. Returns `0` for pre-epoch system clocks. The `u128` return type cannot overflow for any representable `SystemTime`.

**Example:**

```rust
use clock_lib::Wall;

let nanos = Wall::now().unix_nanos();
assert!(nanos > 0);
```

<br>

## Constants

### `VERSION`

```rust
pub const VERSION: &str
```

The crate version string, populated by Cargo at build time. Useful for embedding the running clock-lib version in logs or diagnostics.

**Example:**

```rust
println!("clock-lib {}", clock_lib::VERSION);
```