Skip to main content

saluki_common/
time.rs

1//! Time-related functions.
2
3use std::{
4    fmt::{self, Write as _},
5    ops::Range,
6    str::FromStr,
7    sync::{
8        atomic::{AtomicU64, Ordering::Relaxed},
9        Once, OnceLock,
10    },
11    thread,
12    time::{Duration, SystemTime},
13};
14
15use jiff::{
16    fmt::{temporal::DateTimePrinter, StdFmtWrite},
17    tz::Offset,
18    Unit,
19};
20use saluki_error::{generic_error, GenericError};
21
22static COARSE_TIME_INITIALIZED: Once = Once::new();
23static COARSE_TIME: AtomicU64 = AtomicU64::new(0);
24const COARSE_TIME_UPDATE_INTERVAL: Duration = Duration::from_millis(250);
25
26/// Get the current Unix timestamp, in seconds.
27///
28/// This function is accurate, as it always retrieves the current time for each call. In scenarios where this function
29/// is being called frequently, it may pose an unacceptable performance overhead. In such cases, consider using
30/// `get_coarse_unix_timestamp`, which provides a cached value that's updated periodically.
31pub fn get_unix_timestamp() -> u64 {
32    let since_unix_epoch = SystemTime::now()
33        .duration_since(SystemTime::UNIX_EPOCH)
34        .unwrap_or_default();
35    since_unix_epoch.as_secs()
36}
37
38/// Get the current Unix timestamp, in nanoseconds.
39///
40/// Like `get_unix_timestamp`, this function always retrieves the current time for each call.
41pub fn get_unix_timestamp_nanos() -> u64 {
42    let since_unix_epoch = SystemTime::now()
43        .duration_since(SystemTime::UNIX_EPOCH)
44        .unwrap_or_default();
45    since_unix_epoch.as_nanos() as u64
46}
47
48/// Get the current coarse Unix timestamp, in seconds.
49///
50/// In scenarios where the current Unix timestamp is needed frequently, this function provides a cached value that's
51/// updated periodically. As the precision of the timestamp is one second, this function allows trading off accuracy
52/// (see below) for reduced overhead. The resulting value is considered "coarse," because it might be off by significant
53/// percentage of the overall precision.
54///
55/// # Accuracy
56///
57/// The underlying coarse time is updated roughly every 250 milliseconds, so the value returned by this function may be
58/// behind by up to 250 milliseconds. This means that if calling the function at true time `t` (where `t` is in
59/// seconds), the value returned may be `t-1` _or_ `t`, but will never be behind by more than 250 milliseconds, and
60/// never _ahead_ of `t`.
61pub fn get_coarse_unix_timestamp() -> u64 {
62    // Initialize a background thread to update the coarse time if it hasn't been initialized yet.
63    COARSE_TIME_INITIALIZED.call_once(|| {
64        // Initialize the coarse time with the current Unix timestamp.
65        COARSE_TIME.store(get_unix_timestamp(), Relaxed);
66
67        thread::spawn(|| {
68            loop {
69                // Sleep for 250 milliseconds.
70                thread::sleep(COARSE_TIME_UPDATE_INTERVAL);
71
72                // Update the coarse time with the current Unix timestamp.
73                COARSE_TIME.store(get_unix_timestamp(), Relaxed);
74            }
75        });
76    });
77
78    COARSE_TIME.load(Relaxed)
79}
80
81/// A point in time, with nanosecond precision.
82///
83/// Write it with [`Timestamp::format`], or parse it from RFC 3339 with [`str::parse`]. It can represent any time from
84/// the year -9999 to 9999-12-30T22:00:00Z.
85#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
86pub struct Timestamp(jiff::Timestamp);
87
88impl Timestamp {
89    /// The Unix epoch, 1970-01-01T00:00:00Z.
90    pub const UNIX_EPOCH: Self = Self(jiff::Timestamp::UNIX_EPOCH);
91
92    /// Gets the current time.
93    ///
94    /// # Errors
95    ///
96    /// If the system clock is outside of the range that `Timestamp` supports, an error is returned.
97    pub fn now() -> Result<Self, GenericError> {
98        jiff::Timestamp::try_from(SystemTime::now())
99            .map(Self)
100            .map_err(|e| generic_error!("System clock is outside of the supported range: {}", e))
101    }
102
103    /// Creates a `Timestamp` from a number of seconds since the Unix epoch, or `None` if it's out of range.
104    pub fn from_unix_seconds(seconds: i64) -> Option<Self> {
105        jiff::Timestamp::from_second(seconds).ok().map(Self)
106    }
107
108    /// Creates a `Timestamp` from a number of milliseconds since the Unix epoch, or `None` if it's out of range.
109    pub fn from_unix_millis(millis: i64) -> Option<Self> {
110        jiff::Timestamp::from_millisecond(millis).ok().map(Self)
111    }
112
113    /// Creates a `Timestamp` from a number of nanoseconds since the Unix epoch, or `None` if it's out of range.
114    pub fn from_unix_nanos(nanos: i128) -> Option<Self> {
115        jiff::Timestamp::from_nanosecond(nanos).ok().map(Self)
116    }
117
118    /// Returns the number of whole milliseconds since the Unix epoch, rounded down to the earlier millisecond.
119    pub fn as_unix_millis(self) -> i64 {
120        // jiff truncates toward zero, so a time before the epoch with a fractional millisecond needs one less.
121        let millis = self.0.as_millisecond();
122        if self.0.subsec_nanosecond() % 1_000_000 < 0 {
123            millis - 1
124        } else {
125            millis
126        }
127    }
128
129    /// Returns the number of nanoseconds since the Unix epoch.
130    pub fn as_unix_nanos(self) -> i128 {
131        self.0.as_nanosecond()
132    }
133
134    /// Returns the number of whole seconds from `earlier` to this timestamp, rounded toward zero.
135    ///
136    /// The result is negative if `earlier` is actually later, such as when the system clock went backwards.
137    pub fn whole_seconds_since(self, earlier: Self) -> i64 {
138        self.0.duration_since(earlier.0).as_secs()
139    }
140
141    /// Returns a value that writes this timestamp in the given format.
142    pub fn format(self, format: TimestampFormat<'_>) -> FormattedTimestamp<'_> {
143        FormattedTimestamp {
144            timestamp: self,
145            format,
146        }
147    }
148}
149
150impl FromStr for Timestamp {
151    type Err = GenericError;
152
153    fn from_str(input: &str) -> Result<Self, Self::Err> {
154        input
155            .parse()
156            .map(Self)
157            .map_err(|e| generic_error!("Invalid RFC 3339 timestamp '{}': {}", input, e))
158    }
159}
160
161/// A time zone, for writing a [`Timestamp`] as local time.
162#[derive(Clone, Debug)]
163pub struct TimeZone(jiff::tz::TimeZone);
164
165impl TimeZone {
166    /// Gets UTC.
167    pub fn utc() -> &'static Self {
168        static UTC: TimeZone = TimeZone(jiff::tz::TimeZone::UTC);
169        &UTC
170    }
171
172    /// Gets the local time zone of the system.
173    ///
174    /// The time zone is detected on the first call and reused for the life of the process. If the `TZ` environment
175    /// variable is set, it alone decides the time zone: a value that can't be resolved gives UTC, without looking
176    /// anywhere else. Otherwise, the time zone comes from `/etc/localtime` on Unix or the system settings on Windows,
177    /// falling back to UTC if no time zone can be found.
178    ///
179    /// The first call may read the system's time zone database from disk, so make it during startup rather than on a
180    /// hot path.
181    pub fn system() -> &'static Self {
182        static SYSTEM: OnceLock<TimeZone> = OnceLock::new();
183        SYSTEM.get_or_init(|| Self(jiff::tz::TimeZone::try_system().unwrap_or(jiff::tz::TimeZone::UTC)))
184    }
185
186    /// Creates a time zone from a POSIX `TZ` rule, such as `EST5EDT,M3.2.0,M11.1.0`.
187    ///
188    /// # Errors
189    ///
190    /// If the rule isn't valid, an error is returned.
191    pub fn posix(rule: &str) -> Result<Self, GenericError> {
192        jiff::tz::TimeZone::posix(rule)
193            .map(Self)
194            .map_err(|e| generic_error!("Invalid POSIX time zone rule '{}': {}", rule, e))
195    }
196}
197
198/// A format for writing a [`Timestamp`].
199///
200/// The examples are all 2024-12-31T23:59:59.123456789Z, written in `America/New_York` where the format takes a time
201/// zone. Formats in whole seconds or milliseconds truncate the rest, toward the earlier time.
202#[derive(Clone, Copy, Debug)]
203pub enum TimestampFormat<'a> {
204    /// RFC 3339 with a numeric offset: `2024-12-31T18:59:59.123456789-05:00`.
205    ///
206    /// Fractional seconds use the fewest of 0, 3, 6, or 9 digits that represent the timestamp exactly, and UTC is
207    /// written as `+00:00` rather than `Z`.
208    ///
209    /// RFC 3339 can only write offsets in whole minutes and under 24 hours. An offset with seconds, such as `-01:00:30`
210    /// from `TZ=TST1:00:30`, is rounded to the nearest minute, and the local time shifts by up to 30 seconds to match,
211    /// so that the timestamp still names the same instant. The last example in section 5.8 of RFC 3339 does the same.
212    /// An offset that rounds to 24 hours or more is replaced by UTC.
213    Rfc3339(&'a TimeZone),
214
215    /// RFC 3339 in UTC, in whole seconds: `2024-12-31T23:59:59Z`.
216    Rfc3339UtcSeconds,
217
218    /// RFC 3339 in UTC, in milliseconds: `2024-12-31T23:59:59.123Z`.
219    Rfc3339UtcMillis,
220
221    /// Date and time, in whole seconds: `2024-12-31 18:59:59`.
222    DateTime(&'a TimeZone),
223
224    /// Date and time, in whole seconds, followed by the time zone's abbreviation: `2024-12-31 18:59:59 EST`.
225    DateTimeWithAbbreviation(&'a TimeZone),
226
227    /// Go's default layout for a time in UTC, in whole seconds: `2024-12-31 23:59:59 +0000 UTC`.
228    GoUtc,
229
230    /// Date and time without separators except between them, in whole seconds: `20241231-185959`.
231    CompactDateTime(&'a TimeZone),
232
233    /// Time of day, in whole seconds: `18:59:59`.
234    TimeOfDay(&'a TimeZone),
235
236    /// Date and time in UTC, without separators and with nine fractional digits: `20241231235959123456789`.
237    ///
238    /// Parse it with [`parse_compact_utc_nanos`].
239    CompactUtcNanos,
240}
241
242/// A [`Timestamp`] to be written in a [`TimestampFormat`], returned by [`Timestamp::format`].
243#[derive(Clone, Copy, Debug)]
244pub struct FormattedTimestamp<'a> {
245    timestamp: Timestamp,
246    format: TimestampFormat<'a>,
247}
248
249impl fmt::Display for FormattedTimestamp<'_> {
250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251        let timestamp = self.timestamp.0;
252        match self.format {
253            TimestampFormat::Rfc3339(tz) => write_rfc3339(f, timestamp, rfc3339_offset(tz.0.to_offset(timestamp))),
254            TimestampFormat::Rfc3339UtcSeconds => write_rfc3339_utc(f, timestamp, 0),
255            TimestampFormat::Rfc3339UtcMillis => write_rfc3339_utc(f, timestamp, 3),
256            TimestampFormat::DateTime(tz) => write_date_time(f, &tz.0.to_datetime(timestamp)),
257            TimestampFormat::DateTimeWithAbbreviation(tz) => {
258                let info = tz.0.to_offset_info(timestamp);
259                write_date_time(f, &info.offset().to_datetime(timestamp))?;
260                write!(f, " {}", info.abbreviation())
261            }
262            TimestampFormat::GoUtc => {
263                write_date_time(f, &Offset::UTC.to_datetime(timestamp))?;
264                f.write_str(" +0000 UTC")
265            }
266            TimestampFormat::CompactDateTime(tz) => {
267                let dt = tz.0.to_datetime(timestamp);
268                write_year(f, dt.year())?;
269                write!(
270                    f,
271                    "{:02}{:02}-{:02}{:02}{:02}",
272                    dt.month(),
273                    dt.day(),
274                    dt.hour(),
275                    dt.minute(),
276                    dt.second()
277                )
278            }
279            TimestampFormat::TimeOfDay(tz) => {
280                let dt = tz.0.to_datetime(timestamp);
281                write!(f, "{:02}:{:02}:{:02}", dt.hour(), dt.minute(), dt.second())
282            }
283            TimestampFormat::CompactUtcNanos => {
284                let dt = Offset::UTC.to_datetime(timestamp);
285                write_year(f, dt.year())?;
286                write!(
287                    f,
288                    "{:02}{:02}{:02}{:02}{:02}{:09}",
289                    dt.month(),
290                    dt.day(),
291                    dt.hour(),
292                    dt.minute(),
293                    dt.second(),
294                    dt.subsec_nanosecond()
295                )
296            }
297        }
298    }
299}
300
301/// Parses a timestamp written in [`TimestampFormat::CompactUtcNanos`] into nanoseconds since the Unix epoch.
302///
303/// Returns `None` unless the input is exactly 23 digits that make a valid date and time. Unlike [`Timestamp`], this
304/// works up to the end of the year 9999.
305pub fn parse_compact_utc_nanos(input: &str) -> Option<i128> {
306    let digits = input.as_bytes();
307    if digits.len() != 23 || !digits.iter().all(u8::is_ascii_digit) {
308        return None;
309    }
310
311    let field = |range: Range<usize>| {
312        digits[range]
313            .iter()
314            .fold(0i32, |value, digit| value * 10 + i32::from(digit - b'0'))
315    };
316    let datetime = jiff::civil::DateTime::new(
317        i16::try_from(field(0..4)).ok()?,
318        i8::try_from(field(4..6)).ok()?,
319        i8::try_from(field(6..8)).ok()?,
320        i8::try_from(field(8..10)).ok()?,
321        i8::try_from(field(10..12)).ok()?,
322        i8::try_from(field(12..14)).ok()?,
323        field(14..23),
324    )
325    .ok()?;
326
327    // Subtracting civil datetimes, rather than converting to a `Timestamp`, works up to the end of the year 9999.
328    let since_epoch = datetime.duration_since(jiff::civil::DateTime::constant(1970, 1, 1, 0, 0, 0, 0));
329    Some(since_epoch.as_nanos())
330}
331
332/// Returns the offset to write in RFC 3339 for `offset`: rounded to the nearest minute, or UTC if that's 24 hours or
333/// more.
334fn rfc3339_offset(offset: Offset) -> Offset {
335    // Rounding only fails when the result is outside of jiff's offset range, which is also 24 hours or more.
336    match offset.round(Unit::Minute) {
337        Ok(rounded) if rounded.seconds().abs() < 24 * 60 * 60 => rounded,
338        _ => Offset::UTC,
339    }
340}
341
342fn write_rfc3339(f: &mut fmt::Formatter<'_>, timestamp: jiff::Timestamp, offset: Offset) -> fmt::Result {
343    let nanos = offset.to_datetime(timestamp).subsec_nanosecond();
344    let precision = if nanos == 0 {
345        0
346    } else if nanos % 1_000_000 == 0 {
347        3
348    } else if nanos % 1_000 == 0 {
349        6
350    } else {
351        9
352    };
353
354    DateTimePrinter::new()
355        .precision(Some(precision))
356        .print_timestamp_with_offset(&timestamp, offset, StdFmtWrite(f))
357        .map_err(|_| fmt::Error)
358}
359
360fn write_rfc3339_utc(f: &mut fmt::Formatter<'_>, timestamp: jiff::Timestamp, precision: u8) -> fmt::Result {
361    DateTimePrinter::new()
362        .precision(Some(precision))
363        .print_timestamp(&timestamp, StdFmtWrite(f))
364        .map_err(|_| fmt::Error)
365}
366
367fn write_date_time(f: &mut fmt::Formatter<'_>, dt: &jiff::civil::DateTime) -> fmt::Result {
368    write_year(f, dt.year())?;
369    write!(
370        f,
371        "-{:02}-{:02} {:02}:{:02}:{:02}",
372        dt.month(),
373        dt.day(),
374        dt.hour(),
375        dt.minute(),
376        dt.second()
377    )
378}
379
380/// Writes a year with at least four digits, and a sign only when it's negative.
381fn write_year(f: &mut fmt::Formatter<'_>, year: i16) -> fmt::Result {
382    if year < 0 {
383        f.write_char('-')?;
384    }
385    write!(f, "{:04}", year.unsigned_abs())
386}
387
388#[cfg(test)]
389mod tests {
390    use std::{thread::sleep, time::Duration};
391
392    use super::*;
393
394    // 2024-12-31T23:59:59Z
395    const SECS: i64 = 1_735_689_599;
396
397    fn at(secs: i64, nanos: i32) -> Timestamp {
398        Timestamp(jiff::Timestamp::new(secs, nanos).expect("test timestamp should be valid"))
399    }
400
401    fn fixed(seconds: i32) -> TimeZone {
402        let offset = Offset::from_seconds(seconds).expect("test offset should be valid");
403        TimeZone(jiff::tz::TimeZone::fixed(offset))
404    }
405
406    // Matches the current rules of `America/New_York`, without depending on the host's time zone database.
407    fn new_york() -> TimeZone {
408        TimeZone::posix("EST5EDT,M3.2.0,M11.1.0").expect("test zone should be valid")
409    }
410
411    #[test]
412    fn every_format_writes_its_documented_example() {
413        let timestamp = at(SECS, 123_456_789);
414        let tz = new_york();
415        let cases = [
416            (TimestampFormat::Rfc3339(&tz), "2024-12-31T18:59:59.123456789-05:00"),
417            (TimestampFormat::Rfc3339UtcSeconds, "2024-12-31T23:59:59Z"),
418            (TimestampFormat::Rfc3339UtcMillis, "2024-12-31T23:59:59.123Z"),
419            (TimestampFormat::DateTime(&tz), "2024-12-31 18:59:59"),
420            (
421                TimestampFormat::DateTimeWithAbbreviation(&tz),
422                "2024-12-31 18:59:59 EST",
423            ),
424            (TimestampFormat::GoUtc, "2024-12-31 23:59:59 +0000 UTC"),
425            (TimestampFormat::CompactDateTime(&tz), "20241231-185959"),
426            (TimestampFormat::TimeOfDay(&tz), "18:59:59"),
427            (TimestampFormat::CompactUtcNanos, "20241231235959123456789"),
428        ];
429
430        for (format, expected) in cases {
431            assert_eq!(timestamp.format(format).to_string(), expected, "{format:?}");
432        }
433    }
434
435    #[test]
436    fn local_formats_follow_daylight_saving_time() {
437        // 2024-07-08T22:46:44Z, during daylight saving time in New York.
438        let timestamp = at(1_720_478_804, 0);
439        let tz = new_york();
440        let cases = [
441            (TimestampFormat::Rfc3339(&tz), "2024-07-08T18:46:44-04:00"),
442            (
443                TimestampFormat::DateTimeWithAbbreviation(&tz),
444                "2024-07-08 18:46:44 EDT",
445            ),
446            (TimestampFormat::CompactDateTime(&tz), "20240708-184644"),
447            (TimestampFormat::TimeOfDay(&tz), "18:46:44"),
448        ];
449
450        for (format, expected) in cases {
451            assert_eq!(timestamp.format(format).to_string(), expected, "{format:?}");
452        }
453    }
454
455    #[test]
456    fn coarse_formats_truncate_toward_the_earlier_time() {
457        let utc = TimeZone::utc();
458        let cases = [
459            (
460                at(SECS, 999_999_999),
461                TimestampFormat::Rfc3339UtcSeconds,
462                "2024-12-31T23:59:59Z",
463            ),
464            (
465                at(SECS, 999_999_999),
466                TimestampFormat::Rfc3339UtcMillis,
467                "2024-12-31T23:59:59.999Z",
468            ),
469            (
470                at(SECS, 999_999_999),
471                TimestampFormat::DateTime(utc),
472                "2024-12-31 23:59:59",
473            ),
474            (
475                at(SECS, 999_999_999),
476                TimestampFormat::GoUtc,
477                "2024-12-31 23:59:59 +0000 UTC",
478            ),
479            (at(SECS, 999_999_999), TimestampFormat::TimeOfDay(utc), "23:59:59"),
480            // Half a second before the epoch is still in the previous second.
481            (
482                at(0, -500_000_000),
483                TimestampFormat::Rfc3339UtcSeconds,
484                "1969-12-31T23:59:59Z",
485            ),
486            (
487                at(0, -500_000_000),
488                TimestampFormat::Rfc3339UtcMillis,
489                "1969-12-31T23:59:59.500Z",
490            ),
491            (
492                at(0, -500_000_000),
493                TimestampFormat::DateTime(utc),
494                "1969-12-31 23:59:59",
495            ),
496        ];
497
498        for (timestamp, format, expected) in cases {
499            assert_eq!(
500                timestamp.format(format).to_string(),
501                expected,
502                "{timestamp:?} {format:?}"
503            );
504        }
505    }
506
507    #[test]
508    fn negative_years_have_a_sign_and_four_digits() {
509        let datetime = jiff::civil::DateTime::constant(-1, 6, 15, 12, 0, 0, 0);
510        let timestamp = Timestamp(
511            Offset::UTC
512                .to_timestamp(datetime)
513                .expect("test timestamp should be valid"),
514        );
515        let utc = TimeZone::utc();
516        let cases = [
517            (TimestampFormat::DateTime(utc), "-0001-06-15 12:00:00"),
518            (TimestampFormat::CompactDateTime(utc), "-00010615-120000"),
519            (TimestampFormat::CompactUtcNanos, "-00010615120000000000000"),
520        ];
521
522        for (format, expected) in cases {
523            assert_eq!(timestamp.format(format).to_string(), expected, "{format:?}");
524        }
525    }
526
527    #[test]
528    fn rfc3339_uses_the_fewest_exact_fraction_digits_and_a_numeric_offset() {
529        let utc = TimeZone::utc();
530        let minus_five = fixed(-5 * 60 * 60);
531        let cases = [
532            (0, utc, "2024-12-31T23:59:59+00:00"),
533            (1, utc, "2024-12-31T23:59:59.000000001+00:00"),
534            (1_000, utc, "2024-12-31T23:59:59.000001+00:00"),
535            (1_000_000, utc, "2024-12-31T23:59:59.001+00:00"),
536            (120_000_000, utc, "2024-12-31T23:59:59.120+00:00"),
537            (123_400_000, utc, "2024-12-31T23:59:59.123400+00:00"),
538            (123_456_789, utc, "2024-12-31T23:59:59.123456789+00:00"),
539            (500_000_000, &minus_five, "2024-12-31T18:59:59.500-05:00"),
540        ];
541
542        for (nanos, tz, expected) in cases {
543            let actual = at(SECS, nanos).format(TimestampFormat::Rfc3339(tz)).to_string();
544            assert_eq!(actual, expected, "nanos {nanos}");
545        }
546    }
547
548    // Checks each `(offset in seconds, expected output)` case at 2024-12-31T23:59:59Z, and that the output parses back
549    // to the same instant.
550    fn assert_rfc3339_offset_cases(cases: &[(i32, &str)]) {
551        let timestamp = at(SECS, 0);
552        for &(seconds, expected) in cases {
553            let actual = timestamp.format(TimestampFormat::Rfc3339(&fixed(seconds))).to_string();
554            assert_eq!(actual, expected, "offset {seconds}");
555
556            let parsed: Timestamp = actual.parse().expect("output should parse");
557            assert_eq!(parsed, timestamp, "offset {seconds}");
558        }
559    }
560
561    #[test]
562    fn rfc3339_rounds_offsets_with_seconds_and_shifts_the_local_time_to_match() {
563        // Halves round away from zero. jiff's printer rounds the offset too, but on its own it would keep the local
564        // time exact, which names an instant up to 30 seconds away.
565        assert_rfc3339_offset_cases(&[
566            (-3_600, "2024-12-31T22:59:59-01:00"),
567            (19_800, "2025-01-01T05:29:59+05:30"),
568            (-3_629, "2024-12-31T22:59:59-01:00"),
569            (-3_630, "2024-12-31T22:58:59-01:01"),
570            (19_829, "2025-01-01T05:29:59+05:30"),
571            (19_830, "2025-01-01T05:30:59+05:31"),
572            (-17_762, "2024-12-31T19:03:59-04:56"),
573            (30, "2025-01-01T00:00:59+00:01"),
574            (-30, "2024-12-31T23:58:59-00:01"),
575            // Offsets that round to zero are `+00:00`, because RFC 3339 uses `-00:00` for an unknown local offset.
576            (29, "2024-12-31T23:59:59+00:00"),
577            (-29, "2024-12-31T23:59:59+00:00"),
578            (86_369, "2025-01-01T23:58:59+23:59"),
579            (-86_369, "2024-12-31T00:00:59-23:59"),
580        ]);
581    }
582
583    #[test]
584    fn rfc3339_uses_utc_for_offsets_that_round_to_24_hours_or_more() {
585        assert_rfc3339_offset_cases(&[
586            (86_370, "2024-12-31T23:59:59+00:00"),
587            (-86_370, "2024-12-31T23:59:59+00:00"),
588            (86_400, "2024-12-31T23:59:59+00:00"),
589            (-86_400, "2024-12-31T23:59:59+00:00"),
590            (Offset::MAX.seconds(), "2024-12-31T23:59:59+00:00"),
591            (Offset::MIN.seconds(), "2024-12-31T23:59:59+00:00"),
592        ]);
593    }
594
595    #[test]
596    fn rfc3339_uses_the_civil_fraction_before_the_epoch() {
597        // One nanosecond before the epoch is 23:59:59.999999999 on the previous day, not a negative fraction.
598        let timestamp = at(0, -1);
599        assert_eq!(
600            timestamp.format(TimestampFormat::Rfc3339(TimeZone::utc())).to_string(),
601            "1969-12-31T23:59:59.999999999+00:00"
602        );
603    }
604
605    #[test]
606    fn compact_utc_nanos_parse_back_to_the_same_instant() {
607        let timestamps = [
608            Timestamp::UNIX_EPOCH,
609            at(SECS, 123_456_789),
610            at(SECS, 1),
611            at(0, -1),
612            at(253_402_207_200, 999_999_999),
613        ];
614
615        for timestamp in timestamps {
616            let written = timestamp.format(TimestampFormat::CompactUtcNanos).to_string();
617            assert_eq!(
618                parse_compact_utc_nanos(&written),
619                Some(timestamp.as_unix_nanos()),
620                "{written}"
621            );
622        }
623    }
624
625    #[test]
626    fn compact_utc_nanos_parse_past_the_range_of_timestamp() {
627        assert_eq!(
628            parse_compact_utc_nanos("99991231235959999999999"),
629            Some(253_402_300_799_999_999_999)
630        );
631    }
632
633    #[test]
634    fn compact_utc_nanos_reject_anything_but_23_digits_of_a_valid_date_and_time() {
635        let cases = [
636            "",
637            "2024123123595912345678",
638            "202412312359591234567890",
639            "2024123123595912345678x",
640            "+0241231235959123456789",
641            "20241331235959000000000",
642            "20240230000000000000000",
643            "20241231240000000000000",
644            "20241231235960000000000",
645            "20241231235959123456789",
646        ];
647
648        for input in cases {
649            assert_eq!(parse_compact_utc_nanos(input), None, "{input}");
650        }
651    }
652
653    #[test]
654    fn unix_conversions_cover_the_supported_range() {
655        assert_eq!(Timestamp::from_unix_seconds(0), Some(Timestamp::UNIX_EPOCH));
656        assert_eq!(
657            Timestamp::from_unix_seconds(253_402_207_200),
658            Some(at(253_402_207_200, 0))
659        );
660        assert_eq!(Timestamp::from_unix_seconds(253_402_207_201), None);
661        assert_eq!(Timestamp::from_unix_seconds(i64::MIN), None);
662        assert_eq!(
663            Timestamp::from_unix_millis(253_402_207_200_000),
664            Some(at(253_402_207_200, 0))
665        );
666        assert_eq!(Timestamp::from_unix_millis(253_402_207_200_001), None);
667        assert_eq!(Timestamp::from_unix_nanos(-1), Some(at(0, -1)));
668        assert_eq!(Timestamp::from_unix_nanos(i128::MAX), None);
669
670        assert_eq!(at(SECS, 123_456_789).as_unix_nanos(), 1_735_689_599_123_456_789);
671        assert_eq!(at(SECS, 123_999_999).as_unix_millis(), 1_735_689_599_123);
672        assert_eq!(at(0, -1).as_unix_millis(), -1);
673        assert_eq!(at(0, -1_000_000).as_unix_millis(), -1);
674        assert_eq!(at(0, -1_999_999).as_unix_millis(), -2);
675        assert_eq!(at(-2, -500_000_000).as_unix_millis(), -2_500);
676    }
677
678    #[test]
679    fn whole_seconds_since_rounds_toward_zero() {
680        let started = at(1_795_000_000, 500_000_000);
681        assert_eq!(at(1_795_000_090, 200_000_000).whole_seconds_since(started), 89);
682        assert_eq!(at(1_795_000_090, 500_000_000).whole_seconds_since(started), 90);
683        assert_eq!(at(1_794_999_970, 800_000_000).whole_seconds_since(started), -29);
684    }
685
686    #[test]
687    fn parses_rfc3339() {
688        let expected = at(SECS, 123_000_000);
689        for input in ["2024-12-31T23:59:59.123Z", "2024-12-31T18:59:59.123-05:00"] {
690            assert_eq!(
691                input.parse::<Timestamp>().expect("input should parse"),
692                expected,
693                "{input}"
694            );
695        }
696
697        let error = "yesterday".parse::<Timestamp>().expect_err("input should not parse");
698        assert!(error.to_string().contains("'yesterday'"), "{error}");
699    }
700
701    #[test]
702    fn now_reads_the_system_clock() {
703        let since_epoch = || {
704            SystemTime::now()
705                .duration_since(SystemTime::UNIX_EPOCH)
706                .expect("clock should be after the epoch")
707                .as_nanos() as i128
708        };
709
710        let before = since_epoch();
711        let now = Timestamp::now().expect("clock should be in range").as_unix_nanos();
712        let after = since_epoch();
713        assert!((before..=after).contains(&now), "{now} not in {before}..={after}");
714    }
715
716    #[test]
717    fn invalid_posix_rules_are_rejected() {
718        assert!(TimeZone::posix("not a rule").is_err());
719    }
720
721    #[cfg(windows)]
722    #[test]
723    fn time_zone_detection_works_on_windows_with_the_bundled_database() {
724        // Windows has no IANA time zone database, so detection relies on the bundled one. This calls jiff directly
725        // because `TimeZone::system` hides a failure by falling back to UTC. It fails if `TZ` is set to a time zone
726        // that can't be resolved.
727        assert!(jiff::tz::TimeZone::try_system().is_ok());
728    }
729
730    #[test]
731    fn coarse_timestamp_never_exceeds_accurate_timestamp() {
732        // The documented contract is that the coarse timestamp is never _ahead_ of the true time:
733        // it is only ever equal to it or lagging behind it, because it is a cached snapshot of a
734        // previous `get_unix_timestamp()` call. Sample repeatedly to make an accidental "ahead"
735        // read unlikely to slip through.
736        for _ in 0..1_000 {
737            let coarse = get_coarse_unix_timestamp();
738            let accurate = get_unix_timestamp();
739            assert!(
740                coarse <= accurate,
741                "coarse timestamp {coarse} must never be ahead of accurate timestamp {accurate}"
742            );
743        }
744    }
745
746    #[test]
747    fn coarse_timestamp_is_monotonically_non_decreasing() {
748        // The coarse timestamp is only ever replaced with a newer `get_unix_timestamp()` value, so
749        // successive reads must never go backwards, including across an update-interval boundary.
750        let first = get_coarse_unix_timestamp();
751
752        let mut previous = first;
753        for _ in 0..1_000 {
754            let current = get_coarse_unix_timestamp();
755            assert!(
756                current >= previous,
757                "coarse timestamp went backwards: {previous} -> {current}"
758            );
759            previous = current;
760        }
761
762        // Sleep past a couple of update intervals so the background updater runs, then confirm the
763        // value has not regressed.
764        sleep(COARSE_TIME_UPDATE_INTERVAL * 3);
765        let after_sleep = get_coarse_unix_timestamp();
766        assert!(
767            after_sleep >= previous,
768            "coarse timestamp regressed after update: {previous} -> {after_sleep}"
769        );
770    }
771
772    #[test]
773    fn coarse_timestamp_tracks_accurate_within_staleness_bound() {
774        // The documented staleness bound is that the coarse value may lag true time by at most
775        // ~250ms, i.e. in whole seconds it is either `t` or `t-1`. Once the background updater is
776        // running, the difference against the accurate timestamp should therefore be no more than
777        // one second. Retry across a short window to absorb one-off scheduling jitter on busy CI.
778        get_coarse_unix_timestamp();
779        sleep(COARSE_TIME_UPDATE_INTERVAL * 2);
780
781        let mut within_bound = false;
782        for _ in 0..20 {
783            let accurate = get_unix_timestamp();
784            let coarse = get_coarse_unix_timestamp();
785            if accurate - coarse <= 1 {
786                within_bound = true;
787                break;
788            }
789            sleep(Duration::from_millis(100));
790        }
791
792        assert!(
793            within_bound,
794            "coarse timestamp never came within one second of the accurate timestamp"
795        );
796    }
797}