Skip to main content

time_tour/
time-tour.rs

1//! The values in one pass: instants and spans, the calendar, a stamped value, and a counter's rate.
2//!
3//! ```text
4//! cargo run -p t2t --example time-tour
5//! ```
6
7#![expect(clippy::print_stdout, reason = "a tour prints what it finds")]
8
9use t2t::{TickRate, Tickdelta, Tickstamp, Timed, Timedelta, Timestamp};
10
11/// What a weather station measured, worth stamping.
12#[derive(Debug, Clone, Copy)]
13struct Weather {
14    /// The temperature, in degrees Celsius.
15    celsius: i16,
16    /// The relative humidity, in percent.
17    humidity: u8,
18}
19
20fn main() {
21    // A span is written and read the way a config spells it.
22    let stale = Timedelta::SECOND;
23    println!("stale after        {stale}");
24    println!("\"1h30m\" reads as   {:?}", "1h30m".parse::<Timedelta>());
25
26    // An instant is a point; the difference of two is a span.
27    let published = Timestamp::from_secs(1_700_000_000);
28    let captured = published + Timedelta::from_micros(850);
29    println!("published          {published}");
30    println!("captured           {captured:.6}");
31    println!("on the wire        {}", captured - published);
32
33    // The same instant, read as a date; and the minute it falls in.
34    let date_time = captured.to_utc();
35    println!(
36        "that is            {}-{:02}-{:02}, {} ns past the second",
37        date_time.year, date_time.month, date_time.day, date_time.nanosecond
38    );
39    let minute = captured.floor(Timedelta::MINUTE);
40    println!("its minute         {minute:.0} to {:.0}", minute + Timedelta::MINUTE);
41
42    // A value carries the stamp its writer captured it with, and says how old it is.
43    let sample = Timed::new(captured, Weather { celsius: 21, humidity: 40 });
44    let age = sample.elapsed(captured + Timedelta::from_millis(1_500));
45    println!(
46        "sample             {} °C, {}%, {age} old, stale: {}",
47        sample.celsius,
48        sample.humidity,
49        age > stale
50    );
51
52    // A counter's ticks mean nothing until a rate says what one is worth.
53    let start = Tickstamp::from_ticks(1_000_000);
54    let ticks = start + Tickdelta::from_ticks(4_250) - start;
55    let rate = TickRate::GIGAHERTZ;
56    println!("counter ran        {ticks}: {} at {rate}", ticks.to_timedelta(rate));
57}