Skip to main content

nautilus_core/
datetime.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Common data and time functions.
17use 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
27/// Number of milliseconds in one second.
28pub const MILLISECONDS_IN_SECOND: u64 = 1_000;
29
30/// Number of nanoseconds in one second.
31pub const NANOSECONDS_IN_SECOND: u64 = 1_000_000_000;
32
33/// Number of nanoseconds in one millisecond.
34pub const NANOSECONDS_IN_MILLISECOND: u64 = 1_000_000;
35const NANOSECONDS_IN_MILLISECOND_U32: u32 = 1_000_000;
36
37/// Number of nanoseconds in one microsecond.
38pub const NANOSECONDS_IN_MICROSECOND: u64 = 1_000;
39
40/// Number of nanoseconds in one minute.
41pub const NANOSECONDS_IN_MINUTE: u64 = 60 * NANOSECONDS_IN_SECOND;
42
43/// Number of nanoseconds in one day.
44pub const NANOSECONDS_IN_DAY: u64 = 24 * 60 * NANOSECONDS_IN_MINUTE;
45
46/// Number of seconds in one minute.
47pub const SECONDS_IN_MINUTE: u64 = SECONDS_IN_MINUTE_U32 as u64;
48const SECONDS_IN_MINUTE_U32: u32 = 60;
49
50/// Number of seconds in one hour.
51pub const SECONDS_IN_HOUR: u64 = SECONDS_IN_HOUR_U32 as u64;
52const SECONDS_IN_HOUR_U32: u32 = 60 * SECONDS_IN_MINUTE_U32;
53
54/// Number of seconds in one day.
55pub 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
66// Compile-time checks for time constants to prevent accidental modification
67const _: () = {
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
83/// Resolves an IANA time zone from the bundled database.
84///
85/// The bundled database is intentional: it keeps time zone behavior deterministic across hosts
86/// and avoids system time zone I/O in latency-sensitive paths.
87///
88/// # Errors
89///
90/// Returns an error if `name` is not present in the bundled IANA database.
91pub 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    // Howard Hinnant's civil calendar algorithm maps UTC epoch days to a
97    // Gregorian date using integer arithmetic only. The input is already UTC,
98    // so no timezone or leap-second rules are involved in this formatter.
99    // UnixNanos covers UTC day indexes 0..=213_503; every calendar intermediate fits u32.
100    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
217/// List of weekdays (Monday to Friday).
218pub const WEEKDAYS: [Weekday; 5] = [
219    Weekday::Monday,
220    Weekday::Tuesday,
221    Weekday::Wednesday,
222    Weekday::Thursday,
223    Weekday::Friday,
224];
225
226/// Converts seconds to nanoseconds (ns), rounding to the nearest nanosecond.
227///
228/// # Errors
229///
230/// Returns an error if `secs` is non-finite or cannot be represented as `u64` nanoseconds.
231#[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/// Converts seconds to milliseconds (ms), rounding to the nearest millisecond.
251///
252/// # Errors
253///
254/// Returns an error if `secs` is non-finite or cannot be represented as `u64` milliseconds.
255#[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/// Converts seconds to nanoseconds (ns), panicking on invalid input.
275///
276/// This is a convenience wrapper around [`secs_to_nanos`] when the caller expects
277/// the input to be trusted and in-range.
278///
279/// # Panics
280///
281/// Panics if [`secs_to_nanos`] would return an error for `secs`.
282#[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/// Converts minutes to seconds.
288///
289/// # Panics
290///
291/// Panics if the result cannot be represented as `u64` seconds.
292#[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/// Converts minutes to seconds, returning `None` on overflow.
298#[must_use]
299pub const fn checked_mins_to_secs(mins: u64) -> Option<u64> {
300    mins.checked_mul(SECONDS_IN_MINUTE)
301}
302
303/// Converts milliseconds (ms) to nanoseconds (ns), rounding to the nearest nanosecond.
304///
305/// Returns 0 for a negative input.
306///
307/// # Errors
308///
309/// Returns an error if `millis` is non-finite or cannot be represented as `u64` nanoseconds.
310#[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/// Converts milliseconds (ms) to nanoseconds (ns), panicking on invalid input.
334///
335/// # Panics
336///
337/// Panics if [`millis_to_nanos`] would return an error for `millis`.
338#[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/// Converts microseconds (μs) to nanoseconds (ns), rounding to the nearest nanosecond.
344///
345/// Returns 0 for a negative input.
346///
347/// # Errors
348///
349/// Returns an error if `micros` is non-finite or cannot be represented as `u64` nanoseconds.
350#[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/// Converts microseconds (μs) to nanoseconds (ns), panicking on invalid input.
374///
375/// # Panics
376///
377/// Panics if [`micros_to_nanos`] would return an error for `micros`.
378#[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/// Converts nanoseconds (ns) to seconds.
384///
385/// Casting u64 to f64 may lose precision for large values,
386/// but is acceptable when computing fractional seconds.
387#[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/// Converts nanoseconds (ns) to milliseconds (ms).
399#[must_use]
400pub const fn nanos_to_millis(nanos: u64) -> u64 {
401    nanos / NANOSECONDS_IN_MILLISECOND
402}
403
404/// Converts nanoseconds (ns) to microseconds (μs).
405#[must_use]
406pub const fn nanos_to_micros(nanos: u64) -> u64 {
407    nanos / NANOSECONDS_IN_MICROSECOND
408}
409
410/// Converts a UNIX nanoseconds timestamp to an ISO 8601 (RFC 3339) format string.
411///
412/// All [`UnixNanos`] values are representable by this formatter.
413#[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/// Converts an ISO 8601 (RFC 3339) format string to UNIX nanoseconds timestamp.
434///
435/// This function accepts various ISO 8601 formats including:
436/// - Full RFC 3339 with nanosecond precision: "2024-02-10T14:58:43.456789Z"
437/// - RFC 3339 without fractional seconds: "2024-02-10T14:58:43Z"
438/// - Simple date format: "2024-02-10" (interpreted as midnight UTC)
439///
440/// # Parameters
441///
442/// - `date_string`: The ISO 8601 formatted date string to parse
443///
444/// # Returns
445///
446/// Returns `Ok(UnixNanos)` if the string is successfully parsed, or an error if the format
447/// is invalid or the timestamp is out of range.
448///
449/// # Errors
450///
451/// Returns an error if:
452/// - The string format is not a valid ISO 8601 format.
453/// - The timestamp is out of range for `UnixNanos`.
454/// - The date/time values are invalid.
455#[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/// Converts a UNIX nanoseconds timestamp to an ISO 8601 (RFC 3339) format string
463/// with millisecond precision.
464///
465/// All [`UnixNanos`] values are representable by this formatter.
466#[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/// Floor the given UNIX nanoseconds to the nearest microsecond.
490#[must_use]
491pub const fn floor_to_nearest_microsecond(unix_nanos: u64) -> u64 {
492    (unix_nanos / NANOSECONDS_IN_MICROSECOND) * NANOSECONDS_IN_MICROSECOND
493}
494
495/// Calculates the last weekday (Mon-Fri) from the given `year`, `month`, and `day`.
496///
497/// # Errors
498///
499/// Returns an error if the date is invalid.
500pub 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    // Calculate the offset in days for closest weekday (Mon-Fri)
510    let offset = match current_weekday {
511        1..=5 => 0, // Monday to Friday, no adjustment needed
512        6 => 1,     // Saturday, adjust to previous Friday
513        _ => 2,     // Sunday, adjust to previous Friday
514    };
515    // Calculate last closest weekday
516    let last_closest = date.checked_sub(Span::new().days(offset))?;
517
518    // Convert to UNIX nanoseconds
519    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
530/// Check whether the given UNIX nanoseconds timestamp is within the last 24 hours.
531///
532/// # Errors
533///
534/// Returns an error if the timestamp is invalid.
535pub fn is_within_last_24_hours(timestamp_ns: UnixNanos) -> anyhow::Result<bool> {
536    // Use the time seam so the comparison is deterministic under
537    // `simulation` + `cfg(madsim)` and we avoid a wall-clock call that
538    // would otherwise bypass the DST contract.
539    let timestamp_ns = timestamp_ns.as_u64();
540    let now_ns = nanos_since_unix_epoch();
541
542    // Future timestamps are not within the last 24 hours
543    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
556/// Subtract `n` months from a Jiff [`Timestamp`].
557///
558/// # Errors
559///
560/// Returns an error if the resulting date would be invalid or out of range.
561pub 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
566/// Add `n` months to a Jiff [`Timestamp`].
567///
568/// # Errors
569///
570/// Returns an error if the resulting date would be invalid or out of range.
571pub 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
576/// Subtract `n` months from a given UNIX nanoseconds timestamp.
577///
578/// # Errors
579///
580/// Returns an error if the resulting timestamp is out of range or invalid.
581pub 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
591/// Add `n` months to a given UNIX nanoseconds timestamp.
592///
593/// # Errors
594///
595/// Returns an error if the resulting timestamp is out of range or invalid.
596pub 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
606/// Add `n` years to a Jiff [`Timestamp`].
607///
608/// # Errors
609///
610/// Returns an error if the resulting date would be invalid or out of range.
611pub 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
620/// Subtract `n` years from a Jiff [`Timestamp`].
621///
622/// # Errors
623///
624/// Returns an error if the resulting date would be invalid or out of range.
625pub 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
634/// Add `n` years to a given UNIX nanoseconds timestamp.
635///
636/// # Errors
637///
638/// Returns an error if the resulting timestamp is out of range or invalid.
639pub 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
649/// Subtract `n` years from a given UNIX nanoseconds timestamp.
650///
651/// # Errors
652///
653/// Returns an error if the resulting timestamp is out of range or invalid.
654pub 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
664/// Convert an optional [`Timestamp`] to an optional [`UnixNanos`] timestamp.
665pub 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
672/// Converts a `Timestamp` to `UnixNanos`.
673///
674/// Unlike `UnixNanos::from(Timestamp)` which panics, this returns an error.
675///
676/// # Errors
677///
678/// Returns an error if the timestamp is before the UNIX epoch or out of range for `UnixNanos`.
679pub 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` not `expect`: nightly clippy does not fire `float_cmp` inside `assert_eq!`
693#[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")] // Unix epoch
918    #[case(1, "1970-01-01T00:00:00.000000001Z")] // 1 nanosecond
919    #[case(1_000, "1970-01-01T00:00:00.000001000Z")] // 1 microsecond
920    #[case(1_000_000, "1970-01-01T00:00:00.001000000Z")] // 1 millisecond
921    #[case(1_000_000_000, "1970-01-01T00:00:01.000000000Z")] // 1 second
922    #[case(951_782_400_000_000_000, "2000-02-29T00:00:00.000000000Z")] // Leap day
923    #[case(1_609_459_199_999_999_999, "2020-12-31T23:59:59.999999999Z")] // Year boundary
924    #[case(1_702_857_600_000_000_000, "2023-12-18T00:00:00.000000000Z")] // Specific date
925    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)] // 1970-03-01, civil leap-cycle boundary
937    #[case(5_356_800_000_000_000)] // 1970-03-04, civil leap-cycle boundary
938    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")] // Unix epoch
961    #[case(1_000_000, "1970-01-01T00:00:00.001Z")] // 1 millisecond
962    #[case(1_000_000_000, "1970-01-01T00:00:01.000Z")] // 1 second
963    #[case(951_782_400_123_456_789, "2000-02-29T00:00:00.123Z")] // Leap day
964    #[case(1_609_459_199_999_999_999, "2020-12-31T23:59:59.999Z")] // Year boundary
965    #[case(1_702_857_600_123_456_789, "2023-12-18T00:00:00.123Z")] // With millisecond precision
966    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    // Sweep the full representable range against Jiff, complementing the fixed-point oracle
998    // cases above; any divergence in the integer date math surfaces as a mismatch here.
999    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)] // Fri
1023    #[case(2023, 12, 16, 1_702_598_400_000_000_000)] // Sat
1024    #[case(2023, 12, 17, 1_702_598_400_000_000_000)] // Sun
1025    #[case(2023, 12, 18, 1_702_857_600_000_000_000)] // Mon
1026    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        // Future timestamps should return false
1071        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        // One day in the future should also return false
1077        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)] // Unix epoch
1166    #[case("1970-01-01T00:00:00.000000001Z", 1)] // 1 nanosecond
1167    #[case("1970-01-01T00:00:00.001000000Z", 1_000_000)] // 1 millisecond
1168    #[case("1970-01-01T00:00:01.000000000Z", 1_000_000_000)] // 1 second
1169    #[case("2023-12-18T00:00:00.000000000Z", 1_702_857_600_000_000_000)] // Specific date
1170    #[case("2024-02-10T14:58:43.456789Z", 1_707_577_123_456_789_000)] // RFC3339 with fractions
1171    #[case("2024-02-10T14:58:43Z", 1_707_577_123_000_000_000)] // RFC3339 without fractions
1172    #[case("2024-02-10", 1_707_523_200_000_000_000)] // Simple date format
1173    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")] // Invalid format
1180    #[case("2024-02-30")] // Invalid date
1181    #[case("2024-13-01")] // Invalid month
1182    #[case("not a timestamp")] // Random string
1183    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        // Test adding 1 year from 2020-01-01
1199        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        // Test adding 1 month from 2020-01-15
1208        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        // Adding a year to the epoch can never go negative, this pins the exact value
1217        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        // Unix epoch (1970-01-01 00:00:00 UTC) should return 0 nanoseconds
1225        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        // Expected: 1705325445123456789 nanoseconds
1236        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        // Pre-epoch datetime (1969-12-31 23:59:59 UTC) should return None
1243        // because negative timestamps can't be converted to u64
1244        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        // 1970-01-01 00:00:01 UTC = 1_000_000_000 nanoseconds
1252        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        // Test with microseconds: 1970-01-01 00:00:00.000001 UTC
1260        let dt = Timestamp::new(0, 1_000).unwrap(); // 1 microsecond = 1000 nanos
1261        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}