1use std::{convert::TryFrom, sync::LazyLock};
18
19use jiff::{
20 Span, Timestamp,
21 civil::{Date, Weekday},
22 tz::{TimeZone, TimeZoneDatabase},
23};
24
25use crate::{UnixNanos, time::nanos_since_unix_epoch};
26
27pub const MILLISECONDS_IN_SECOND: u64 = 1_000;
29
30pub const NANOSECONDS_IN_SECOND: u64 = 1_000_000_000;
32
33pub const NANOSECONDS_IN_MILLISECOND: u64 = 1_000_000;
35const NANOSECONDS_IN_MILLISECOND_U32: u32 = 1_000_000;
36
37pub const NANOSECONDS_IN_MICROSECOND: u64 = 1_000;
39
40pub const NANOSECONDS_IN_MINUTE: u64 = 60 * NANOSECONDS_IN_SECOND;
42
43pub const NANOSECONDS_IN_DAY: u64 = 24 * 60 * NANOSECONDS_IN_MINUTE;
45
46pub const SECONDS_IN_MINUTE: u64 = SECONDS_IN_MINUTE_U32 as u64;
48const SECONDS_IN_MINUTE_U32: u32 = 60;
49
50pub const SECONDS_IN_HOUR: u64 = SECONDS_IN_HOUR_U32 as u64;
52const SECONDS_IN_HOUR_U32: u32 = 60 * SECONDS_IN_MINUTE_U32;
53
54pub const SECONDS_IN_DAY: u64 = 24 * SECONDS_IN_HOUR;
56
57#[expect(
58 clippy::cast_precision_loss,
59 reason = "u64::MAX rounds to the exact exclusive 2^64 upper bound"
60)]
61pub(crate) const U64_UPPER_BOUND_F64: f64 = u64::MAX as f64;
62
63static BUNDLED_TIME_ZONE_DATABASE: LazyLock<TimeZoneDatabase> =
64 LazyLock::new(TimeZoneDatabase::bundled);
65
66const _: () = {
68 assert!(NANOSECONDS_IN_SECOND == 1_000_000_000);
69 assert!(NANOSECONDS_IN_MILLISECOND == 1_000_000);
70 assert!(NANOSECONDS_IN_MICROSECOND == 1_000);
71 assert!(MILLISECONDS_IN_SECOND == 1_000);
72 assert!(NANOSECONDS_IN_SECOND == MILLISECONDS_IN_SECOND * NANOSECONDS_IN_MILLISECOND);
73 assert!(NANOSECONDS_IN_MILLISECOND == NANOSECONDS_IN_MICROSECOND * 1_000);
74 assert!(NANOSECONDS_IN_SECOND / NANOSECONDS_IN_MILLISECOND == 1_000);
75 assert!(NANOSECONDS_IN_SECOND / NANOSECONDS_IN_MICROSECOND == 1_000_000);
76 assert!(SECONDS_IN_MINUTE == 60);
77 assert!(SECONDS_IN_HOUR == 3_600);
78 assert!(SECONDS_IN_DAY == 86_400);
79 assert!(NANOSECONDS_IN_MINUTE == 60 * NANOSECONDS_IN_SECOND);
80 assert!(NANOSECONDS_IN_DAY == 24 * 60 * NANOSECONDS_IN_MINUTE);
81};
82
83pub fn get_timezone(name: &str) -> Result<TimeZone, jiff::Error> {
92 BUNDLED_TIME_ZONE_DATABASE.get(name)
93}
94
95fn civil_from_days(days_since_epoch: u32) -> (i32, u32, u32) {
96 let z = days_since_epoch + 719_468;
101 let era = z / 146_097;
102 let day_of_era = z - era * 146_097;
103 let year_of_era =
104 (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
105 let year = year_of_era + era * 400;
106 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
107 let month_prime = (5 * day_of_year + 2) / 153;
108 let day = day_of_year - (153 * month_prime + 2) / 5 + 1;
109 let month = if month_prime < 10 {
110 month_prime + 3
111 } else {
112 month_prime - 9
113 };
114 let year = year + u32::from(month <= 2);
115
116 (i32::try_from(year).expect("year fits in i32"), month, day)
117}
118
119struct DateTimeParts {
120 year: i32,
121 month: u32,
122 day: u32,
123 hour: u32,
124 minute: u32,
125 second: u32,
126 subsec_nanos: u32,
127}
128
129#[expect(
130 clippy::cast_possible_truncation,
131 reason = "digit writers only receive values in 0..=9"
132)]
133fn push_digit(out: &mut String, digit: u32) {
134 out.push(char::from(b'0' + digit as u8));
135}
136
137const DIGIT_PAIRS: &str = concat!(
138 "0001020304050607080910111213141516171819",
139 "2021222324252627282930313233343536373839",
140 "4041424344454647484950515253545556575859",
141 "6061626364656667686970717273747576777879",
142 "8081828384858687888990919293949596979899",
143);
144
145fn push_2_digits(out: &mut String, value: u32) {
146 debug_assert!(value < 100);
147 let offset = value as usize * 2;
148 out.push_str(&DIGIT_PAIRS[offset..offset + 2]);
149}
150
151fn push_3_digits(out: &mut String, value: u32) {
152 debug_assert!(value < 1_000);
153 push_digit(out, value / 100);
154 push_2_digits(out, value % 100);
155}
156
157fn push_4_digits(out: &mut String, value: i32) {
158 debug_assert!((0..=9_999).contains(&value));
159 let value = u32::try_from(value).expect("year is non-negative");
160 push_2_digits(out, value / 100);
161 push_2_digits(out, value % 100);
162}
163
164fn push_9_digits(out: &mut String, value: u32) {
165 debug_assert!(value < 1_000_000_000);
166 push_3_digits(out, value / 1_000_000);
167 push_3_digits(out, value / 1_000 % 1_000);
168 push_3_digits(out, value % 1_000);
169}
170
171fn split_unix_nanos(unix_nanos: UnixNanos) -> DateTimeParts {
172 let nanos = unix_nanos.as_u64();
173 let total_seconds = nanos / NANOSECONDS_IN_SECOND;
174 let subsec_nanos = u32::try_from(nanos % NANOSECONDS_IN_SECOND).expect("subsecond fits u32");
175 let days = u32::try_from(total_seconds / SECONDS_IN_DAY).expect("days since epoch fits u32");
176 let seconds_of_day =
177 u32::try_from(total_seconds % SECONDS_IN_DAY).expect("seconds of day fits u32");
178 let (year, month, day) = civil_from_days(days);
179 let hour = seconds_of_day / SECONDS_IN_HOUR_U32;
180 let minute = (seconds_of_day % SECONDS_IN_HOUR_U32) / SECONDS_IN_MINUTE_U32;
181 let second = seconds_of_day % SECONDS_IN_MINUTE_U32;
182
183 DateTimeParts {
184 year,
185 month,
186 day,
187 hour,
188 minute,
189 second,
190 subsec_nanos,
191 }
192}
193
194fn push_iso8601_prefix(
195 out: &mut String,
196 year: i32,
197 month: u32,
198 day: u32,
199 hour: u32,
200 minute: u32,
201 second: u32,
202) {
203 push_4_digits(out, year);
204 out.push('-');
205 push_2_digits(out, month);
206 out.push('-');
207 push_2_digits(out, day);
208 out.push('T');
209 push_2_digits(out, hour);
210 out.push(':');
211 push_2_digits(out, minute);
212 out.push(':');
213 push_2_digits(out, second);
214 out.push('.');
215}
216
217pub const WEEKDAYS: [Weekday; 5] = [
219 Weekday::Monday,
220 Weekday::Tuesday,
221 Weekday::Wednesday,
222 Weekday::Thursday,
223 Weekday::Friday,
224];
225
226#[expect(
232 clippy::cast_possible_truncation,
233 clippy::cast_sign_loss,
234 clippy::cast_precision_loss,
235 reason = "Intentional for unit conversion, may lose precision after clamping"
236)]
237pub fn secs_to_nanos(secs: f64) -> anyhow::Result<u64> {
238 anyhow::ensure!(secs.is_finite(), "seconds must be finite, was {secs}");
239 if secs <= 0.0 {
240 return Ok(0);
241 }
242 let nanos = secs * NANOSECONDS_IN_SECOND as f64;
243 anyhow::ensure!(
244 nanos < U64_UPPER_BOUND_F64,
245 "seconds {secs} is out of range for `u64` nanoseconds"
246 );
247 Ok(nanos.round() as u64)
248}
249
250#[expect(
256 clippy::cast_possible_truncation,
257 clippy::cast_sign_loss,
258 clippy::cast_precision_loss,
259 reason = "Intentional for unit conversion, may lose precision after clamping"
260)]
261pub fn secs_to_millis(secs: f64) -> anyhow::Result<u64> {
262 anyhow::ensure!(secs.is_finite(), "seconds must be finite, was {secs}");
263 if secs <= 0.0 {
264 return Ok(0);
265 }
266 let millis = secs * MILLISECONDS_IN_SECOND as f64;
267 anyhow::ensure!(
268 millis < U64_UPPER_BOUND_F64,
269 "seconds {secs} is out of range for `u64` milliseconds"
270 );
271 Ok(millis.round() as u64)
272}
273
274#[must_use]
283pub fn secs_to_nanos_unchecked(secs: f64) -> u64 {
284 secs_to_nanos(secs).expect("secs_to_nanos_unchecked: invalid or overflowing input")
285}
286
287#[must_use]
293pub const fn mins_to_secs(mins: u64) -> u64 {
294 checked_mins_to_secs(mins).expect("minutes to seconds conversion overflow")
295}
296
297#[must_use]
299pub const fn checked_mins_to_secs(mins: u64) -> Option<u64> {
300 mins.checked_mul(SECONDS_IN_MINUTE)
301}
302
303#[expect(
311 clippy::cast_possible_truncation,
312 clippy::cast_sign_loss,
313 clippy::cast_precision_loss,
314 reason = "Intentional for unit conversion, may lose precision after clamping"
315)]
316pub fn millis_to_nanos(millis: f64) -> anyhow::Result<u64> {
317 anyhow::ensure!(
318 millis.is_finite(),
319 "milliseconds must be finite, was {millis}"
320 );
321
322 if millis <= 0.0 {
323 return Ok(0);
324 }
325 let nanos = millis * NANOSECONDS_IN_MILLISECOND as f64;
326 anyhow::ensure!(
327 nanos < U64_UPPER_BOUND_F64,
328 "milliseconds {millis} is out of range for `u64` nanoseconds"
329 );
330 Ok(nanos.round() as u64)
331}
332
333#[must_use]
339pub fn millis_to_nanos_unchecked(millis: f64) -> u64 {
340 millis_to_nanos(millis).expect("millis_to_nanos_unchecked: invalid or overflowing input")
341}
342
343#[expect(
351 clippy::cast_possible_truncation,
352 clippy::cast_sign_loss,
353 clippy::cast_precision_loss,
354 reason = "Intentional for unit conversion, may lose precision after clamping"
355)]
356pub fn micros_to_nanos(micros: f64) -> anyhow::Result<u64> {
357 anyhow::ensure!(
358 micros.is_finite(),
359 "microseconds must be finite, was {micros}"
360 );
361
362 if micros <= 0.0 {
363 return Ok(0);
364 }
365 let nanos = micros * NANOSECONDS_IN_MICROSECOND as f64;
366 anyhow::ensure!(
367 nanos < U64_UPPER_BOUND_F64,
368 "microseconds {micros} is out of range for `u64` nanoseconds"
369 );
370 Ok(nanos.round() as u64)
371}
372
373#[must_use]
379pub fn micros_to_nanos_unchecked(micros: f64) -> u64 {
380 micros_to_nanos(micros).expect("micros_to_nanos_unchecked: invalid or overflowing input")
381}
382
383#[expect(
388 clippy::cast_precision_loss,
389 reason = "Precision loss acceptable for time conversion"
390)]
391#[must_use]
392pub fn nanos_to_secs(nanos: u64) -> f64 {
393 let seconds = nanos / NANOSECONDS_IN_SECOND;
394 let rem_nanos = nanos % NANOSECONDS_IN_SECOND;
395 (seconds as f64) + (rem_nanos as f64) / (NANOSECONDS_IN_SECOND as f64)
396}
397
398#[must_use]
400pub const fn nanos_to_millis(nanos: u64) -> u64 {
401 nanos / NANOSECONDS_IN_MILLISECOND
402}
403
404#[must_use]
406pub const fn nanos_to_micros(nanos: u64) -> u64 {
407 nanos / NANOSECONDS_IN_MICROSECOND
408}
409
410#[inline]
414#[must_use]
415pub fn unix_nanos_to_iso8601(unix_nanos: UnixNanos) -> String {
416 let parts = split_unix_nanos(unix_nanos);
417
418 let mut out = String::with_capacity(30);
419 push_iso8601_prefix(
420 &mut out,
421 parts.year,
422 parts.month,
423 parts.day,
424 parts.hour,
425 parts.minute,
426 parts.second,
427 );
428 push_9_digits(&mut out, parts.subsec_nanos);
429 out.push('Z');
430 out
431}
432
433#[inline]
456pub fn iso8601_to_unix_nanos(date_string: &str) -> anyhow::Result<UnixNanos> {
457 date_string
458 .parse::<UnixNanos>()
459 .map_err(|e| anyhow::anyhow!("Failed to parse ISO 8601 string '{date_string}': {e}"))
460}
461
462#[inline]
467#[must_use]
468pub fn unix_nanos_to_iso8601_millis(unix_nanos: UnixNanos) -> String {
469 let parts = split_unix_nanos(unix_nanos);
470
471 let mut out = String::with_capacity(24);
472 push_iso8601_prefix(
473 &mut out,
474 parts.year,
475 parts.month,
476 parts.day,
477 parts.hour,
478 parts.minute,
479 parts.second,
480 );
481 push_3_digits(
482 &mut out,
483 parts.subsec_nanos / NANOSECONDS_IN_MILLISECOND_U32,
484 );
485 out.push('Z');
486 out
487}
488
489#[must_use]
491pub const fn floor_to_nearest_microsecond(unix_nanos: u64) -> u64 {
492 (unix_nanos / NANOSECONDS_IN_MICROSECOND) * NANOSECONDS_IN_MICROSECOND
493}
494
495pub fn last_weekday_nanos(year: i32, month: u32, day: u32) -> anyhow::Result<UnixNanos> {
501 let date = Date::new(
502 i16::try_from(year).map_err(|_| anyhow::anyhow!("Invalid date"))?,
503 i8::try_from(month).map_err(|_| anyhow::anyhow!("Invalid date"))?,
504 i8::try_from(day).map_err(|_| anyhow::anyhow!("Invalid date"))?,
505 )
506 .map_err(|_| anyhow::anyhow!("Invalid date"))?;
507 let current_weekday = date.weekday().to_monday_one_offset();
508
509 let offset = match current_weekday {
511 1..=5 => 0, 6 => 1, _ => 2, };
515 let last_closest = date.checked_sub(Span::new().days(offset))?;
517
518 let unix_timestamp_ns = last_closest
520 .at(0, 0, 0, 0)
521 .to_zoned(TimeZone::UTC)?
522 .timestamp()
523 .as_nanosecond();
524
525 let ns_u64 = u64::try_from(unix_timestamp_ns)
526 .map_err(|_| anyhow::anyhow!("Negative timestamp: {unix_timestamp_ns}"))?;
527 Ok(UnixNanos::from(ns_u64))
528}
529
530pub fn is_within_last_24_hours(timestamp_ns: UnixNanos) -> anyhow::Result<bool> {
536 let timestamp_ns = timestamp_ns.as_u64();
540 let now_ns = nanos_since_unix_epoch();
541
542 if timestamp_ns > now_ns {
544 return Ok(false);
545 }
546
547 Ok(now_ns - timestamp_ns <= NANOSECONDS_IN_DAY)
548}
549
550fn shift_months(datetime: Timestamp, months: i64) -> anyhow::Result<Timestamp> {
551 let span = Span::new().try_months(months)?;
552 let result = datetime.to_zoned(TimeZone::UTC).checked_add(span)?;
553 Ok(result.timestamp())
554}
555
556pub fn subtract_n_months(datetime: Timestamp, n: u32) -> anyhow::Result<Timestamp> {
562 shift_months(datetime, -i64::from(n))
563 .map_err(|_| anyhow::anyhow!("Failed to subtract {n} months from {datetime}"))
564}
565
566pub fn add_n_months(datetime: Timestamp, n: u32) -> anyhow::Result<Timestamp> {
572 shift_months(datetime, i64::from(n))
573 .map_err(|_| anyhow::anyhow!("Failed to add {n} months to {datetime}"))
574}
575
576pub fn subtract_n_months_nanos(unix_nanos: UnixNanos, n: u32) -> anyhow::Result<UnixNanos> {
582 let datetime = unix_nanos.to_datetime_utc();
583 let result = subtract_n_months(datetime, n)?;
584 let timestamp = result.as_nanosecond();
585
586 let nanos =
587 u64::try_from(timestamp).map_err(|_| anyhow::anyhow!("Negative timestamp not allowed"))?;
588 Ok(UnixNanos::from(nanos))
589}
590
591pub fn add_n_months_nanos(unix_nanos: UnixNanos, n: u32) -> anyhow::Result<UnixNanos> {
597 let datetime = unix_nanos.to_datetime_utc();
598 let result = add_n_months(datetime, n)?;
599 let timestamp = result.as_nanosecond();
600
601 let nanos =
602 u64::try_from(timestamp).map_err(|_| anyhow::anyhow!("Negative timestamp not allowed"))?;
603 Ok(UnixNanos::from(nanos))
604}
605
606pub fn add_n_years(datetime: Timestamp, n: u32) -> anyhow::Result<Timestamp> {
612 let months = n.checked_mul(12).ok_or_else(|| {
613 anyhow::anyhow!("Failed to add {n} years to {datetime}: month count overflow")
614 })?;
615
616 shift_months(datetime, i64::from(months))
617 .map_err(|_| anyhow::anyhow!("Failed to add {n} years to {datetime}"))
618}
619
620pub fn subtract_n_years(datetime: Timestamp, n: u32) -> anyhow::Result<Timestamp> {
626 let months = n.checked_mul(12).ok_or_else(|| {
627 anyhow::anyhow!("Failed to subtract {n} years from {datetime}: month count overflow")
628 })?;
629
630 shift_months(datetime, -i64::from(months))
631 .map_err(|_| anyhow::anyhow!("Failed to subtract {n} years from {datetime}"))
632}
633
634pub fn add_n_years_nanos(unix_nanos: UnixNanos, n: u32) -> anyhow::Result<UnixNanos> {
640 let datetime = unix_nanos.to_datetime_utc();
641 let result = add_n_years(datetime, n)?;
642 let timestamp = result.as_nanosecond();
643
644 let nanos =
645 u64::try_from(timestamp).map_err(|_| anyhow::anyhow!("Negative timestamp not allowed"))?;
646 Ok(UnixNanos::from(nanos))
647}
648
649pub fn subtract_n_years_nanos(unix_nanos: UnixNanos, n: u32) -> anyhow::Result<UnixNanos> {
655 let datetime = unix_nanos.to_datetime_utc();
656 let result = subtract_n_years(datetime, n)?;
657 let timestamp = result.as_nanosecond();
658
659 let nanos =
660 u64::try_from(timestamp).map_err(|_| anyhow::anyhow!("Negative timestamp not allowed"))?;
661 Ok(UnixNanos::from(nanos))
662}
663
664pub fn datetime_to_unix_nanos(value: Option<Timestamp>) -> Option<UnixNanos> {
666 value
667 .map(Timestamp::as_nanosecond)
668 .and_then(|nanos| u64::try_from(nanos).ok())
669 .map(UnixNanos::from)
670}
671
672pub fn try_datetime_to_unix_nanos(value: Timestamp) -> anyhow::Result<UnixNanos> {
680 let nanos = value.as_nanosecond();
681
682 if nanos < 0 {
683 anyhow::bail!("DateTime timestamp cannot be negative: {nanos}");
684 }
685 let nanos = u64::try_from(nanos)
686 .map_err(|_| anyhow::anyhow!("DateTime timestamp out of range for UnixNanos: {nanos}"))?;
687
688 Ok(UnixNanos::from(nanos))
689}
690
691#[cfg(test)]
692#[allow(
694 clippy::float_cmp,
695 reason = "Exact float comparisons acceptable in tests"
696)]
697mod tests {
698 use jiff::SignedDuration;
699 use proptest::prelude::*;
700 use rstest::rstest;
701
702 use super::*;
703
704 fn timestamp(value: &str) -> Timestamp {
705 value.parse().unwrap()
706 }
707
708 #[rstest]
709 #[case(0.0, 0)]
710 #[case(1.0, 1_000_000_000)]
711 #[case(1.1, 1_100_000_000)]
712 #[case(42.0, 42_000_000_000)]
713 #[case(0.000_123_5, 123_500)]
714 #[case(0.000_000_01, 10)]
715 #[case(0.000_000_001, 1)]
716 #[case(9.999_999_999, 9_999_999_999)]
717 #[case(1.001, 1_001_000_000)]
718 #[case(0.000_000_001_4, 1)]
719 #[case(0.000_000_000_5, 1)]
720 fn test_secs_to_nanos(#[case] value: f64, #[case] expected: u64) {
721 let result = secs_to_nanos(value).unwrap();
722 assert_eq!(result, expected);
723 }
724
725 #[rstest]
726 #[case(0.0, 0)]
727 #[case(1.0, 1_000)]
728 #[case(1.1, 1_100)]
729 #[case(42.0, 42_000)]
730 #[case(0.012_34, 12)]
731 #[case(0.001, 1)]
732 #[case(1.001, 1_001)]
733 fn test_secs_to_millis(#[case] value: f64, #[case] expected: u64) {
734 let result = secs_to_millis(value).unwrap();
735 assert_eq!(result, expected);
736 }
737
738 #[rstest]
739 fn test_secs_to_nanos_unchecked_matches_checked() {
740 assert_eq!(secs_to_nanos_unchecked(1.1), secs_to_nanos(1.1).unwrap());
741 }
742
743 #[rstest]
744 fn test_secs_to_nanos_non_finite_errors() {
745 let err = secs_to_nanos(f64::NAN).unwrap_err();
746 assert!(err.to_string().contains("finite"));
747 }
748
749 #[rstest]
750 fn test_secs_to_millis_non_finite_errors() {
751 let err = secs_to_millis(f64::INFINITY).unwrap_err();
752 assert!(err.to_string().contains("finite"));
753 }
754
755 #[rstest]
756 fn test_millis_to_nanos_non_finite_errors() {
757 let err = millis_to_nanos(f64::NEG_INFINITY).unwrap_err();
758 assert!(err.to_string().contains("finite"));
759 }
760
761 #[rstest]
762 fn test_micros_to_nanos_non_finite_errors() {
763 let err = micros_to_nanos(f64::NAN).unwrap_err();
764 assert!(err.to_string().contains("finite"));
765 }
766
767 #[rstest]
768 #[case(0, 0)]
769 #[case(1, 60)]
770 #[case(5, 300)]
771 #[case(60, 3600)]
772 #[case(1440, 86400)]
773 fn test_mins_to_secs(#[case] mins: u64, #[case] expected: u64) {
774 assert_eq!(mins_to_secs(mins), expected);
775 }
776
777 #[rstest]
778 #[case(
779 checked_mins_to_secs,
780 307_445_734_561_825_860,
781 18_446_744_073_709_551_600
782 )]
783 fn test_checked_minutes_conversion_boundary(
784 #[case] convert: fn(u64) -> Option<u64>,
785 #[case] max: u64,
786 #[case] expected: u64,
787 ) {
788 assert_eq!(convert(max), Some(expected));
789 assert_eq!(convert(max + 1), None);
790 }
791
792 #[rstest]
793 #[should_panic(expected = "minutes to seconds conversion overflow")]
794 fn test_mins_to_secs_overflow_panics() {
795 let _ = mins_to_secs(307_445_734_561_825_861);
796 }
797
798 #[rstest]
799 #[case(
800 secs_to_nanos,
801 18_446_744_073.709_553,
802 18_446_744_073.709_55,
803 18_446_744_073_709_549_568
804 )]
805 #[case(
806 secs_to_millis,
807 18_446_744_073_709_550.0,
808 18_446_744_073_709_548.0,
809 18_446_744_073_709_547_520
810 )]
811 #[case(
812 millis_to_nanos,
813 18_446_744_073_709.55,
814 18_446_744_073_709.547,
815 18_446_744_073_709_547_520
816 )]
817 #[case(
818 micros_to_nanos,
819 18_446_744_073_709_550.0,
820 18_446_744_073_709_548.0,
821 18_446_744_073_709_547_520
822 )]
823 fn test_float_conversion_u64_boundary(
824 #[case] convert: fn(f64) -> anyhow::Result<u64>,
825 #[case] invalid: f64,
826 #[case] previous: f64,
827 #[case] expected: u64,
828 ) {
829 let err = convert(invalid).unwrap_err();
830 assert!(err.to_string().contains("out of range"));
831 assert_eq!(convert(previous).unwrap(), expected);
832 }
833
834 #[rstest]
835 fn test_secs_to_nanos_negative_infinity_errors() {
836 let result = secs_to_nanos(f64::NEG_INFINITY);
837 assert!(result.is_err());
838 }
839
840 #[rstest]
841 #[case(0.0, 0)]
842 #[case(1.0, 1_000_000)]
843 #[case(1.1, 1_100_000)]
844 #[case(42.0, 42_000_000)]
845 #[case(0.000_123_4, 123)]
846 #[case(0.000_01, 10)]
847 #[case(0.000_001, 1)]
848 #[case(9.999_999, 9_999_999)]
849 #[case(1.001, 1_001_000)]
850 fn test_millis_to_nanos(#[case] value: f64, #[case] expected: u64) {
851 let result = millis_to_nanos(value).unwrap();
852 assert_eq!(result, expected);
853 }
854
855 #[rstest]
856 fn test_millis_to_nanos_unchecked_matches_checked() {
857 assert_eq!(
858 millis_to_nanos_unchecked(1.1),
859 millis_to_nanos(1.1).unwrap()
860 );
861 }
862
863 #[rstest]
864 #[case(0.0, 0)]
865 #[case(1.0, 1_000)]
866 #[case(1.1, 1_100)]
867 #[case(42.0, 42_000)]
868 #[case(0.1234, 123)]
869 #[case(0.01, 10)]
870 #[case(0.001, 1)]
871 #[case(9.999, 9_999)]
872 #[case(1.001, 1_001)]
873 fn test_micros_to_nanos(#[case] value: f64, #[case] expected: u64) {
874 let result = micros_to_nanos(value).unwrap();
875 assert_eq!(result, expected);
876 }
877
878 #[rstest]
879 fn test_micros_to_nanos_unchecked_matches_checked() {
880 assert_eq!(
881 micros_to_nanos_unchecked(1.1),
882 micros_to_nanos(1.1).unwrap()
883 );
884 }
885
886 #[rstest]
887 #[case(0, 0.0)]
888 #[case(1, 1e-09)]
889 #[case(1_000_000_000, 1.0)]
890 #[case(42_897_123_111, 42.897_123_111)]
891 fn test_nanos_to_secs(#[case] value: u64, #[case] expected: f64) {
892 let result = nanos_to_secs(value);
893 assert_eq!(result, expected);
894 }
895
896 #[rstest]
897 #[case(0, 0)]
898 #[case(1_000_000, 1)]
899 #[case(1_000_000_000, 1000)]
900 #[case(42_897_123_111, 42897)]
901 fn test_nanos_to_millis(#[case] value: u64, #[case] expected: u64) {
902 let result = nanos_to_millis(value);
903 assert_eq!(result, expected);
904 }
905
906 #[rstest]
907 #[case(0, 0)]
908 #[case(1_000, 1)]
909 #[case(1_000_000_000, 1_000_000)]
910 #[case(42_897_123, 42_897)]
911 fn test_nanos_to_micros(#[case] value: u64, #[case] expected: u64) {
912 let result = nanos_to_micros(value);
913 assert_eq!(result, expected);
914 }
915
916 #[rstest]
917 #[case(0, "1970-01-01T00:00:00.000000000Z")] #[case(1, "1970-01-01T00:00:00.000000001Z")] #[case(1_000, "1970-01-01T00:00:00.000001000Z")] #[case(1_000_000, "1970-01-01T00:00:00.001000000Z")] #[case(1_000_000_000, "1970-01-01T00:00:01.000000000Z")] #[case(951_782_400_000_000_000, "2000-02-29T00:00:00.000000000Z")] #[case(1_609_459_199_999_999_999, "2020-12-31T23:59:59.999999999Z")] #[case(1_702_857_600_000_000_000, "2023-12-18T00:00:00.000000000Z")] fn test_unix_nanos_to_iso8601(#[case] nanos: u64, #[case] expected: &str) {
926 let result = unix_nanos_to_iso8601(UnixNanos::from(nanos));
927 assert_eq!(result, expected);
928 }
929
930 #[rstest]
931 #[case(0)]
932 #[case(1)]
933 #[case(951_782_400_123_456_789)]
934 #[case(1_609_459_199_999_999_999)]
935 #[case(i64::MAX as u64)]
936 #[case(5_097_600_000_000_000)] #[case(5_356_800_000_000_000)] fn test_unix_nanos_to_iso8601_matches_jiff_oracle(#[case] nanos: u64) {
939 let expected = format!(
940 "{:.9}",
941 Timestamp::from_nanosecond(i128::from(nanos)).unwrap()
942 );
943 let result = unix_nanos_to_iso8601(UnixNanos::from(nanos));
944 assert_eq!(result, expected);
945 }
946
947 #[rstest]
948 #[case((i64::MAX as u64) + 1)]
949 #[case(u64::MAX)]
950 fn test_unix_nanos_to_iso8601_supports_full_unix_nanos_range(#[case] nanos: u64) {
951 let expected = format!(
952 "{:.9}",
953 Timestamp::from_nanosecond(i128::from(nanos)).unwrap()
954 );
955 let result = unix_nanos_to_iso8601(UnixNanos::from(nanos));
956 assert_eq!(result, expected);
957 }
958
959 #[rstest]
960 #[case(0, "1970-01-01T00:00:00.000Z")] #[case(1_000_000, "1970-01-01T00:00:00.001Z")] #[case(1_000_000_000, "1970-01-01T00:00:01.000Z")] #[case(951_782_400_123_456_789, "2000-02-29T00:00:00.123Z")] #[case(1_609_459_199_999_999_999, "2020-12-31T23:59:59.999Z")] #[case(1_702_857_600_123_456_789, "2023-12-18T00:00:00.123Z")] fn test_unix_nanos_to_iso8601_millis(#[case] nanos: u64, #[case] expected: &str) {
967 let result = unix_nanos_to_iso8601_millis(UnixNanos::from(nanos));
968 assert_eq!(result, expected);
969 }
970
971 #[rstest]
972 #[case(0)]
973 #[case(951_782_400_123_456_789)]
974 #[case(1_609_459_199_999_999_999)]
975 #[case(i64::MAX as u64)]
976 fn test_unix_nanos_to_iso8601_millis_matches_jiff_oracle(#[case] nanos: u64) {
977 let expected = format!(
978 "{:.3}",
979 Timestamp::from_nanosecond(i128::from(nanos)).unwrap()
980 );
981 let result = unix_nanos_to_iso8601_millis(UnixNanos::from(nanos));
982 assert_eq!(result, expected);
983 }
984
985 #[rstest]
986 #[case((i64::MAX as u64) + 1)]
987 #[case(u64::MAX)]
988 fn test_unix_nanos_to_iso8601_millis_supports_full_unix_nanos_range(#[case] nanos: u64) {
989 let expected = format!(
990 "{:.3}",
991 Timestamp::from_nanosecond(i128::from(nanos)).unwrap()
992 );
993 let result = unix_nanos_to_iso8601_millis(UnixNanos::from(nanos));
994 assert_eq!(result, expected);
995 }
996
997 proptest! {
1000 #[rstest]
1001 fn prop_unix_nanos_to_iso8601_matches_jiff(nanos in any::<u64>()) {
1002 let expected = format!(
1003 "{:.9}",
1004 Timestamp::from_nanosecond(i128::from(nanos)).unwrap(),
1005 );
1006 let actual = unix_nanos_to_iso8601(UnixNanos::from(nanos));
1007 prop_assert_eq!(actual, expected);
1008 }
1009
1010 #[rstest]
1011 fn prop_unix_nanos_to_iso8601_millis_matches_jiff(nanos in any::<u64>()) {
1012 let expected = format!(
1013 "{:.3}",
1014 Timestamp::from_nanosecond(i128::from(nanos)).unwrap(),
1015 );
1016 let actual = unix_nanos_to_iso8601_millis(UnixNanos::from(nanos));
1017 prop_assert_eq!(actual, expected);
1018 }
1019 }
1020
1021 #[rstest]
1022 #[case(2023, 12, 15, 1_702_598_400_000_000_000)] #[case(2023, 12, 16, 1_702_598_400_000_000_000)] #[case(2023, 12, 17, 1_702_598_400_000_000_000)] #[case(2023, 12, 18, 1_702_857_600_000_000_000)] fn test_last_closest_weekday_nanos_with_valid_date(
1027 #[case] year: i32,
1028 #[case] month: u32,
1029 #[case] day: u32,
1030 #[case] expected: u64,
1031 ) {
1032 let result = last_weekday_nanos(year, month, day).unwrap().as_u64();
1033 assert_eq!(result, expected);
1034 }
1035
1036 #[rstest]
1037 fn test_last_closest_weekday_nanos_with_invalid_date() {
1038 let result = last_weekday_nanos(2023, 4, 31);
1039 assert!(result.is_err());
1040 }
1041
1042 #[rstest]
1043 fn test_last_closest_weekday_nanos_with_nonexistent_date() {
1044 let result = last_weekday_nanos(2023, 2, 30);
1045 assert!(result.is_err());
1046 }
1047
1048 #[rstest]
1049 fn test_last_closest_weekday_nanos_with_invalid_conversion() {
1050 let result = last_weekday_nanos(9999, 12, 31);
1051 assert!(result.is_err());
1052 }
1053
1054 #[rstest]
1055 fn test_is_within_last_24_hours_when_now() {
1056 let now_ns = Timestamp::now().as_nanosecond();
1057 assert!(is_within_last_24_hours(UnixNanos::from(u64::try_from(now_ns).unwrap())).unwrap());
1058 }
1059
1060 #[rstest]
1061 fn test_is_within_last_24_hours_when_two_days_ago() {
1062 let past_ns = (Timestamp::now() - SignedDuration::from_hours(48)).as_nanosecond();
1063 assert!(
1064 !is_within_last_24_hours(UnixNanos::from(u64::try_from(past_ns).unwrap())).unwrap()
1065 );
1066 }
1067
1068 #[rstest]
1069 fn test_is_within_last_24_hours_when_future() {
1070 let future_ns = (Timestamp::now() + SignedDuration::from_hours(1)).as_nanosecond();
1072 assert!(
1073 !is_within_last_24_hours(UnixNanos::from(u64::try_from(future_ns).unwrap())).unwrap()
1074 );
1075
1076 let future_ns = (Timestamp::now() + SignedDuration::from_hours(24)).as_nanosecond();
1078 assert!(
1079 !is_within_last_24_hours(UnixNanos::from(u64::try_from(future_ns).unwrap())).unwrap()
1080 );
1081 }
1082
1083 #[rstest]
1084 #[case(
1085 timestamp("2024-03-31T12:00:00Z"),
1086 1,
1087 timestamp("2024-02-29T12:00:00Z")
1088 )]
1089 #[case(
1090 timestamp("2024-03-31T12:00:00Z"),
1091 12,
1092 timestamp("2023-03-31T12:00:00Z")
1093 )]
1094 #[case(
1095 timestamp("2024-01-31T12:00:00Z"),
1096 1,
1097 timestamp("2023-12-31T12:00:00Z")
1098 )]
1099 #[case(
1100 timestamp("2024-03-31T12:00:00Z"),
1101 2,
1102 timestamp("2024-01-31T12:00:00Z")
1103 )]
1104 fn test_subtract_n_months(
1105 #[case] input: Timestamp,
1106 #[case] months: u32,
1107 #[case] expected: Timestamp,
1108 ) {
1109 let result = subtract_n_months(input, months).unwrap();
1110 assert_eq!(result, expected);
1111 }
1112
1113 #[rstest]
1114 #[case(
1115 timestamp("2023-02-28T12:00:00Z"),
1116 1,
1117 timestamp("2023-03-28T12:00:00Z")
1118 )]
1119 #[case(
1120 timestamp("2024-01-31T12:00:00Z"),
1121 1,
1122 timestamp("2024-02-29T12:00:00Z")
1123 )]
1124 #[case(
1125 timestamp("2023-12-31T12:00:00Z"),
1126 1,
1127 timestamp("2024-01-31T12:00:00Z")
1128 )]
1129 #[case(
1130 timestamp("2023-01-31T12:00:00Z"),
1131 13,
1132 timestamp("2024-02-29T12:00:00Z")
1133 )]
1134 fn test_add_n_months(
1135 #[case] input: Timestamp,
1136 #[case] months: u32,
1137 #[case] expected: Timestamp,
1138 ) {
1139 let result = add_n_months(input, months).unwrap();
1140 assert_eq!(result, expected);
1141 }
1142
1143 #[rstest]
1144 fn test_add_n_years_overflow() {
1145 let datetime = timestamp("2024-01-01T00:00:00Z");
1146 let err = add_n_years(datetime, u32::MAX).unwrap_err();
1147 assert!(err.to_string().contains("month count overflow"));
1148 }
1149
1150 #[rstest]
1151 fn test_subtract_n_years_overflow() {
1152 let datetime = timestamp("2024-01-01T00:00:00Z");
1153 let err = subtract_n_years(datetime, u32::MAX).unwrap_err();
1154 assert!(err.to_string().contains("month count overflow"));
1155 }
1156
1157 #[rstest]
1158 fn test_add_n_years_nanos_overflow() {
1159 let nanos = UnixNanos::from(0);
1160 let err = add_n_years_nanos(nanos, u32::MAX).unwrap_err();
1161 assert!(err.to_string().contains("month count overflow"));
1162 }
1163
1164 #[rstest]
1165 #[case("1970-01-01T00:00:00.000000000Z", 0)] #[case("1970-01-01T00:00:00.000000001Z", 1)] #[case("1970-01-01T00:00:00.001000000Z", 1_000_000)] #[case("1970-01-01T00:00:01.000000000Z", 1_000_000_000)] #[case("2023-12-18T00:00:00.000000000Z", 1_702_857_600_000_000_000)] #[case("2024-02-10T14:58:43.456789Z", 1_707_577_123_456_789_000)] #[case("2024-02-10T14:58:43Z", 1_707_577_123_000_000_000)] #[case("2024-02-10", 1_707_523_200_000_000_000)] fn test_iso8601_to_unix_nanos(#[case] input: &str, #[case] expected: u64) {
1174 let result = iso8601_to_unix_nanos(input).unwrap();
1175 assert_eq!(result.as_u64(), expected);
1176 }
1177
1178 #[rstest]
1179 #[case("invalid-date")] #[case("2024-02-30")] #[case("2024-13-01")] #[case("not a timestamp")] fn test_iso8601_to_unix_nanos_invalid(#[case] input: &str) {
1184 let result = iso8601_to_unix_nanos(input);
1185 assert!(result.is_err());
1186 }
1187
1188 #[rstest]
1189 fn test_iso8601_roundtrip() {
1190 let original_nanos = UnixNanos::from(1_707_577_123_456_789_000);
1191 let iso8601_string = unix_nanos_to_iso8601(original_nanos);
1192 let parsed_nanos = iso8601_to_unix_nanos(&iso8601_string).unwrap();
1193 assert_eq!(parsed_nanos, original_nanos);
1194 }
1195
1196 #[rstest]
1197 fn test_add_n_years_nanos_normal_case() {
1198 let start = UnixNanos::from(timestamp("2020-01-01T00:00:00Z"));
1200 let result = add_n_years_nanos(start, 1).unwrap();
1201 let expected = UnixNanos::from(timestamp("2021-01-01T00:00:00Z"));
1202 assert_eq!(result, expected);
1203 }
1204
1205 #[rstest]
1206 fn test_add_n_months_nanos_normal_case() {
1207 let start = UnixNanos::from(timestamp("2020-01-15T00:00:00Z"));
1209 let result = add_n_months_nanos(start, 1).unwrap();
1210 let expected = UnixNanos::from(timestamp("2020-02-15T00:00:00Z"));
1211 assert_eq!(result, expected);
1212 }
1213
1214 #[rstest]
1215 fn test_add_n_years_nanos_from_epoch() {
1216 let start = UnixNanos::from(0);
1218 let result = add_n_years_nanos(start, 1).unwrap();
1219 assert_eq!(result.as_u64(), 31_536_000_000_000_000);
1220 }
1221
1222 #[rstest]
1223 fn test_datetime_to_unix_nanos_at_epoch() {
1224 let epoch = Timestamp::UNIX_EPOCH;
1226 let result = datetime_to_unix_nanos(Some(epoch));
1227 assert_eq!(result, Some(UnixNanos::from(0)));
1228 }
1229
1230 #[rstest]
1231 fn test_datetime_to_unix_nanos_typical_datetime() {
1232 let dt = timestamp("2024-01-15T13:30:45.123456789Z");
1233 let result = datetime_to_unix_nanos(Some(dt));
1234
1235 assert!(result.is_some());
1237 assert_eq!(result.unwrap().as_u64(), 1_705_325_445_123_456_789);
1238 }
1239
1240 #[rstest]
1241 fn test_datetime_to_unix_nanos_before_epoch() {
1242 let before_epoch = timestamp("1969-12-31T23:59:59Z");
1245 let result = datetime_to_unix_nanos(Some(before_epoch));
1246 assert_eq!(result, None);
1247 }
1248
1249 #[rstest]
1250 fn test_datetime_to_unix_nanos_one_second_after_epoch() {
1251 let dt = Timestamp::from_second(1).unwrap();
1253 let result = datetime_to_unix_nanos(Some(dt));
1254 assert_eq!(result, Some(UnixNanos::from(1_000_000_000)));
1255 }
1256
1257 #[rstest]
1258 fn test_datetime_to_unix_nanos_with_subsecond_precision() {
1259 let dt = Timestamp::new(0, 1_000).unwrap(); let result = datetime_to_unix_nanos(Some(dt));
1262 assert_eq!(result, Some(UnixNanos::from(1_000)));
1263 }
1264
1265 #[rstest]
1266 fn test_try_datetime_to_unix_nanos_valid() {
1267 let dt = Timestamp::new(0, 1_000).unwrap();
1268 assert_eq!(
1269 try_datetime_to_unix_nanos(dt).unwrap(),
1270 UnixNanos::from(1_000)
1271 );
1272 }
1273
1274 #[rstest]
1275 fn test_try_datetime_to_unix_nanos_at_epoch() {
1276 assert_eq!(
1277 try_datetime_to_unix_nanos(Timestamp::UNIX_EPOCH).unwrap(),
1278 UnixNanos::from(0)
1279 );
1280 }
1281
1282 #[rstest]
1283 fn test_try_datetime_to_unix_nanos_before_epoch_errors() {
1284 let before_epoch = timestamp("1969-12-31T23:59:59Z");
1285 let err = try_datetime_to_unix_nanos(before_epoch).unwrap_err();
1286 assert!(
1287 err.to_string().contains("cannot be negative"),
1288 "unexpected error: {err}"
1289 );
1290 }
1291
1292 #[rstest]
1293 fn test_try_datetime_to_unix_nanos_out_of_range_errors() {
1294 let err = try_datetime_to_unix_nanos(Timestamp::MAX).unwrap_err();
1295 assert!(
1296 err.to_string().contains("out of range"),
1297 "unexpected error: {err}"
1298 );
1299 }
1300
1301 #[rstest]
1302 fn test_month_and_year_arithmetic_support_values_above_i64_max() {
1303 let large = UnixNanos::from(u64::MAX);
1304 assert!(subtract_n_months_nanos(large, 1).is_ok());
1305 assert!(add_n_months_nanos(large, 1).is_err());
1306 assert!(add_n_years_nanos(large, 1).is_err());
1307 assert!(subtract_n_years_nanos(large, 1).is_ok());
1308 }
1309
1310 #[rstest]
1311 fn test_subtract_n_months_nanos_pre_epoch_result_errors() {
1312 let epoch = UnixNanos::from(0);
1313 let err = subtract_n_months_nanos(epoch, 1).unwrap_err();
1314 assert_eq!(err.to_string(), "Negative timestamp not allowed");
1315 }
1316
1317 #[rstest]
1318 fn test_subtract_n_years_nanos_pre_epoch_result_errors() {
1319 let epoch = UnixNanos::from(0);
1320 let err = subtract_n_years_nanos(epoch, 1).unwrap_err();
1321 assert_eq!(err.to_string(), "Negative timestamp not allowed");
1322 }
1323
1324 #[rstest]
1325 fn test_subtract_n_months_nanos_at_epoch_boundary() {
1326 let epoch = UnixNanos::from(0);
1327 assert_eq!(subtract_n_months_nanos(epoch, 0).unwrap(), epoch);
1328 }
1329
1330 #[rstest]
1331 fn test_get_timezone_with_valid_name() {
1332 let tz = get_timezone("UTC").unwrap();
1333 assert_eq!(tz.iana_name(), Some("UTC"));
1334 }
1335
1336 #[rstest]
1337 fn test_get_timezone_with_unknown_name_errors() {
1338 assert!(get_timezone("Not/A_Zone").is_err());
1339 }
1340
1341 #[rstest]
1342 #[case(0, 0)]
1343 #[case(999, 0)]
1344 #[case(1_000, 1_000)]
1345 #[case(1_000_001, 1_000_000)]
1346 #[case(u64::MAX, 18_446_744_073_709_551_000)]
1347 fn test_floor_to_nearest_microsecond(#[case] input: u64, #[case] expected: u64) {
1348 assert_eq!(floor_to_nearest_microsecond(input), expected);
1349 }
1350
1351 #[rstest]
1352 fn test_formatters_match_jiff_on_every_representable_utc_day() {
1353 for day in 0..=u64::MAX / NANOSECONDS_IN_DAY {
1354 for nanos in [
1355 day * NANOSECONDS_IN_DAY,
1356 (day * NANOSECONDS_IN_DAY).saturating_add(NANOSECONDS_IN_DAY - 1),
1357 ] {
1358 let timestamp = Timestamp::from_nanosecond(i128::from(nanos)).unwrap();
1359 assert_eq!(
1360 unix_nanos_to_iso8601(UnixNanos::from(nanos)),
1361 format!("{timestamp:.9}")
1362 );
1363 assert_eq!(
1364 unix_nanos_to_iso8601_millis(UnixNanos::from(nanos)),
1365 format!("{timestamp:.3}")
1366 );
1367 }
1368 }
1369 }
1370}