1use 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
26pub 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
38pub 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
48pub fn get_coarse_unix_timestamp() -> u64 {
62 COARSE_TIME_INITIALIZED.call_once(|| {
64 COARSE_TIME.store(get_unix_timestamp(), Relaxed);
66
67 thread::spawn(|| {
68 loop {
69 thread::sleep(COARSE_TIME_UPDATE_INTERVAL);
71
72 COARSE_TIME.store(get_unix_timestamp(), Relaxed);
74 }
75 });
76 });
77
78 COARSE_TIME.load(Relaxed)
79}
80
81#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
86pub struct Timestamp(jiff::Timestamp);
87
88impl Timestamp {
89 pub const UNIX_EPOCH: Self = Self(jiff::Timestamp::UNIX_EPOCH);
91
92 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 pub fn from_unix_seconds(seconds: i64) -> Option<Self> {
105 jiff::Timestamp::from_second(seconds).ok().map(Self)
106 }
107
108 pub fn from_unix_millis(millis: i64) -> Option<Self> {
110 jiff::Timestamp::from_millisecond(millis).ok().map(Self)
111 }
112
113 pub fn from_unix_nanos(nanos: i128) -> Option<Self> {
115 jiff::Timestamp::from_nanosecond(nanos).ok().map(Self)
116 }
117
118 pub fn as_unix_millis(self) -> i64 {
120 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 pub fn as_unix_nanos(self) -> i128 {
131 self.0.as_nanosecond()
132 }
133
134 pub fn whole_seconds_since(self, earlier: Self) -> i64 {
138 self.0.duration_since(earlier.0).as_secs()
139 }
140
141 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#[derive(Clone, Debug)]
163pub struct TimeZone(jiff::tz::TimeZone);
164
165impl TimeZone {
166 pub fn utc() -> &'static Self {
168 static UTC: TimeZone = TimeZone(jiff::tz::TimeZone::UTC);
169 &UTC
170 }
171
172 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 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#[derive(Clone, Copy, Debug)]
203pub enum TimestampFormat<'a> {
204 Rfc3339(&'a TimeZone),
214
215 Rfc3339UtcSeconds,
217
218 Rfc3339UtcMillis,
220
221 DateTime(&'a TimeZone),
223
224 DateTimeWithAbbreviation(&'a TimeZone),
226
227 GoUtc,
229
230 CompactDateTime(&'a TimeZone),
232
233 TimeOfDay(&'a TimeZone),
235
236 CompactUtcNanos,
240}
241
242#[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
301pub 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 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
332fn rfc3339_offset(offset: Offset) -> Offset {
335 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(×tamp, 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(×tamp, 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
380fn 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 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 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 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 (
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 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 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 (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 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 assert!(jiff::tz::TimeZone::try_system().is_ok());
728 }
729
730 #[test]
731 fn coarse_timestamp_never_exceeds_accurate_timestamp() {
732 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 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(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 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}