Skip to main content

nanoseconds/
nanoseconds.rs

1//! Sub-second precision conversions using nanosecond types.
2//!
3//! Run with: `cargo run --example nanoseconds`
4
5#![allow(clippy::print_stdout)]
6
7use leap_sec::prelude::*;
8
9fn main() -> Result<(), Error> {
10    let leaps = LeapSeconds::known();
11
12    // A UTC timestamp with sub-second precision (0.5s past the epoch second)
13    let utc_ns = UtcUnixNanos(1_700_000_000_500_000_000);
14
15    // Convert to TAI — the offset (37s) is applied in whole seconds,
16    // the fractional part is preserved exactly
17    let tai_ns = leaps.utc_to_tai_nanos(utc_ns)?;
18    println!("{utc_ns} -> {tai_ns}");
19
20    // Roundtrip preserves precision
21    let back = leaps.tai_to_utc_nanos(tai_ns)?;
22    assert_eq!(back, utc_ns);
23    println!("Roundtrip: {back} (exact match)");
24
25    // Lossless promotion from seconds to nanoseconds
26    let utc_sec = UtcUnixSeconds(1_700_000_000);
27    let promoted: UtcUnixNanos = utc_sec.into();
28    println!("{utc_sec} promoted to {promoted}");
29
30    // Truncate nanoseconds back to seconds (floor)
31    let truncated = utc_ns.to_seconds_floor();
32    println!("{utc_ns} floored to {truncated}");
33
34    Ok(())
35}