Skip to main content

deep_time/dt/
from_str.rs

1use crate::{
2    ATTOS_PER_SEC_I128, Dt, DtErr, DtErrKind, Parts, SEC_PER_DAY, SEC_PER_MONTH, SEC_PER_WEEK,
3    SEC_PER_YEAR, Scale, StrPTimeFmt, an_err,
4};
5use core::str::FromStr;
6
7#[cfg(feature = "parse")]
8use crate::ParseCfg;
9
10#[cfg(feature = "parse")]
11impl FromStr for Dt {
12    type Err = DtErr;
13
14    #[inline]
15    fn from_str(s: &str) -> Result<Self, DtErr> {
16        Dt::from_str_parse(s, &ParseCfg::DEFAULT)
17    }
18}
19
20#[cfg(not(feature = "parse"))]
21impl FromStr for Dt {
22    type Err = DtErr;
23
24    #[inline]
25    fn from_str(s: &str) -> Result<Self, DtErr> {
26        Self::from_str_iso(s)
27    }
28}
29
30struct ParsedComponent {
31    unit: u8,
32    signed_int: i64,
33    frac_digits: usize,
34    frac_num: i64,
35}
36
37impl Dt {
38    /// Parses a date/time string.
39    ///
40    /// - When the `parse` feature is enabled: uses the smart auto-parser.
41    /// - When the `parse` feature is disabled: falls back to the fast ISO 8601 parser
42    ///   ([`Dt::from_str_iso`](../struct.Dt.html#method.from_str_iso)).
43    ///
44    /// ## Examples
45    ///
46    /// ```rust
47    /// use deep_time::{Dt, Scale};
48    ///
49    /// // uses impl FromStr but Dt::parse provides the same functionality
50    /// let x: Dt = "2000-01-01 12:00:00".parse().unwrap();
51    ///
52    /// let ymd = x.to_ymd();
53    /// assert_eq!(ymd.yr(), 2000);
54    /// assert_eq!(ymd.mo(), 1);
55    /// assert_eq!(ymd.day(), 1);
56    /// assert_eq!(ymd.hr(), 12);
57    /// assert_eq!(ymd.min(), 0);
58    /// assert_eq!(ymd.sec(), 0);
59    /// assert_eq!(ymd.attos(), 0);
60    /// ```
61    ///
62    /// ## See also
63    ///
64    /// - [`Dt::from_str_parse`](../struct.Dt.html#method.from_str_parse)
65    /// - [`Dt::from_str_iso`](../struct.Dt.html#method.from_str_iso)
66    #[inline(always)]
67    pub fn parse(s: &str) -> Result<Self, DtErr> {
68        #[cfg(feature = "parse")]
69        {
70            Self::from_str_parse(s, &ParseCfg::DEFAULT)
71        }
72        #[cfg(not(feature = "parse"))]
73        {
74            Self::from_str_iso(s)
75        }
76    }
77
78    /// Parser equivalent to `strptime` with a provided format string.
79    ///
80    /// The returned [`Dt`] will be on the `TAI` time scale, converted from whatever
81    /// optional time scale (`%L`) was provided in the input. If no time scale was
82    /// provided then it's converted from `UTC` -> `TAI`.
83    ///
84    /// The result is that the [`Dt`]'s `scale` field will be `TAI` and its `target`
85    /// field will be whatever time scale it was converted from (`UTC` if no time
86    /// scale was in the input).
87    ///
88    /// ## Parameters
89    ///
90    /// - `fmt`: The format string containing `%` directives.
91    /// - `input`: The string to parse.
92    /// - `inp_can_end_before_fmt`: If `true`, the input may end before the format
93    ///   string is fully consumed (extra format specifiers are ignored).
94    /// - `fmt_can_end_before_inp`: If `true`, the format may end before the input
95    ///   is fully consumed (trailing characters in the input are allowed).
96    /// - `allow_partial_date`: If `true`, a missing month/day will be defaulted
97    ///   to `1` instead of returning a [`DtErrKind::Incomplete`](../error/enum.DtErrKind.html#variant.Incomplete) error.
98    ///
99    /// ## Supported Directives
100    ///
101    /// The format string supports literal characters and the following `%` directives.
102    /// Literal non-whitespace characters must match the input exactly.
103    /// Whitespace in the format matches (and consumes) any leading ASCII whitespace in the input.
104    ///
105    /// Many directives accept **format extensions** right after `%`:
106    /// - **Flags**: `-` (no pad), `_` (space pad), `0` (zero pad), `^`/`#` (treated as default)
107    /// - **Width**: 1–3 digits (affects numeric field width / padding expectations)
108    /// - **Colons** (only for `%z`): `:`, `::`, `:::` to control offset format
109    ///
110    /// ### Year / Century / Unbounded
111    /// - `%Y` — Four-digit year (e.g. `2024`). Supports sign, flags, and width.
112    /// - `%y` — Two-digit year (`00`–`99`; `00`–`68` → 2000+, `69`–`99` → 1900s).
113    /// - `%C` — Century (`00`–`99`).
114    /// - `%G` — Four-digit ISO week-based year.
115    /// - `%g` — Two-digit ISO week-based year (same century rule as `%y`).
116    /// - `%*` — **Unbounded year** (arbitrary length, supports negative years). *Library extension.*
117    ///
118    /// ### Month
119    /// - `%m` — Month number `01`–`12`.
120    /// - `%B` — Full English month name (e.g. `January`).
121    /// - `%b`, `%h` — Abbreviated English month name (3 letters, e.g. `Jan`).
122    ///
123    /// ### Day
124    /// - `%d`, `%e` — Day of month `01`–`31` (`%e` allows space padding).
125    /// - `%j` — Day of year `001`–`366`.
126    ///
127    /// ### Time of day
128    /// - `%H`, `%k` — Hour `00`–`23` (24-hour clock; `%k` allows space padding).
129    /// - `%I`, `%l` — Hour `01`–`12` (12-hour clock).
130    /// - `%M` — Minute `00`–`59`.
131    /// - `%S` — Second `00`–`60` (leap second allowed).
132    /// - `%f`, `%N` — Fractional seconds (up to 18 digits = attoseconds).
133    ///   Width controls precision (`%3f` = ms, `%6N` = µs, `%9f` = ns, etc.).
134    ///   Both accept an optional leading `.` in the input.
135    /// - `%.f`, `%.N`, `%.3f`, `%.6N`, ... — Same fractional parsing, but the
136    ///   dot before the fraction is **optional** in the input (consumes literal `.` if present).
137    /// - `%P`, `%p` — `AM`/`PM` indicator (case-insensitive).
138    ///
139    /// ### Weekday / Week number
140    /// - `%A` — Full English weekday name (e.g. `Monday`).
141    /// - `%a` — Abbreviated English weekday name (3 letters, e.g. `Mon`).
142    /// - `%u` — Weekday number Monday=`1` … Sunday=`7`.
143    /// - `%w` — Weekday number Sunday=`0` … Saturday=`6`.
144    /// - `%U` — Week number (Sunday-first week), `00`–`53`.
145    /// - `%W` — Week number (Monday-first week), `00`–`53`.
146    /// - `%V` — ISO 8601 week number `01`–`53`.
147    ///
148    /// ### Timezone, Offset & Scale
149    /// - `%z` — Timezone offset. Colon count selects format:
150    ///   - `%z`   → `±HH[MM[SS]]` (minutes/seconds optional)
151    ///   - `%:z`  → `±HH:MM` (minutes required)
152    ///   - `%::z` → `±HH:MM:SS` (seconds optional)
153    ///   - `%:::z` → `±HH:MM:SS` (more flexible)
154    /// - `%Q` — IANA timezone name (e.g. `America/New_York`) **or** numeric offset
155    ///   (if input starts with `+`/`-`). *Library extension.*
156    /// - `%L` — Time scale abbreviation (e.g. `TAI`, `UTC`, `GPS`). See [`Scale`].
157    ///   *Library extension.*
158    ///
159    /// ### Shortcuts (compound directives)
160    /// - `%F` — Equivalent to `%Y-%m-%d` (ISO date).
161    /// - `%D` — Equivalent to `%m/%d/%y` (US date).
162    /// - `%T` — Equivalent to `%H:%M:%S`.
163    /// - `%R` — Equivalent to `%H:%M`.
164    ///
165    /// ### Other
166    /// - `%%` — Literal `%` character.
167    /// - `%s` — Unix timestamp (seconds since 1970-01-01 00:00 UTC, can be negative).
168    ///   This directive greedily consumes any fractional seconds.
169    /// - `%J` — Seconds since 2000-01-01 12:00 TAI (2000-01-01 noon epoch), can be
170    ///   negative.
171    ///   This directive greedily consumes any fractional seconds.
172    /// - `%n`, `%t` — Any whitespace (consumes it from input).
173    ///
174    /// ### Unsupported / Unknown
175    /// - `%c`, `%r`, `%x`, `%X`, `%Z` → [`DtErrKind::UnsupportedItem`]
176    /// - Any other unknown directive character → [`DtErrKind::UnknownItem`]
177    ///
178    /// ## Errors
179    ///
180    /// Returns a [`DtErr`] if either the strptime-style parser or the subsequent
181    /// conversion from [`Parts`] to [`Dt`] fails.
182    ///
183    /// ### Format string errors
184    ///
185    /// - [`DtErrKind::TruncatedDirective`] — A `%` appeared at the end of the format
186    ///   string, or after flags/width/colons with no directive character following it.
187    /// - [`DtErrKind::UnexpectedEnd`] — A `%` was followed only by extensions with no
188    ///   directive character.
189    /// - [`DtErrKind::InvalidFractional`] — A `%.` fractional directive was followed by
190    ///   an invalid character (not `f` or `N`).
191    /// - [`DtErrKind::ExpectedFractional`] — A `%.` fractional directive was started
192    ///   but no directive character followed the dot.
193    /// - [`DtErrKind::UnsupportedItem`] — The format contains `%c`, `%r`, `%x`, `%X`,
194    ///   or `%Z`.
195    /// - [`DtErrKind::UnknownItem`] — The format contains an unrecognized `%` directive.
196    ///
197    /// ### Input parsing errors
198    ///
199    /// - [`DtErrKind::UnexpectedEnd`] — The input ended before a required value could
200    ///   be parsed.
201    /// - `Expected*` variants:
202    ///   - [`DtErrKind::ExpectedYear`], [`DtErrKind::ExpectedCentury`],
203    ///     [`DtErrKind::ExpectedMonth`], [`DtErrKind::ExpectedDay`],
204    ///     [`DtErrKind::ExpectedDayOfYear`], [`DtErrKind::ExpectedHour`],
205    ///     [`DtErrKind::ExpectedMinute`], [`DtErrKind::ExpectedSecond`],
206    ///     [`DtErrKind::ExpectedFractional`], [`DtErrKind::ExpectedTimestamp`],
207    ///     [`DtErrKind::ExpectedWeekNumber`], [`DtErrKind::ExpectedMonWeekday`],
208    ///     [`DtErrKind::ExpectedSunWeekday`], [`DtErrKind::ExpectedMonWeek`],
209    ///     [`DtErrKind::ExpectedSunWeek`]
210    /// - Out-of-range errors:
211    ///   - [`DtErrKind::MonthOutOfRange`], [`DtErrKind::DayOutOfRange`],
212    ///     [`DtErrKind::DayOfYearOutOfRange`], [`DtErrKind::HourOutOfRange`],
213    ///     [`DtErrKind::MinuteOutOfRange`], [`DtErrKind::SecondOutOfRange`],
214    ///     [`DtErrKind::IsoWeekOutOfRange`], [`DtErrKind::MonWeekdayOutOfRange`],
215    ///     [`DtErrKind::SunWeekdayOutOfRange`]
216    /// - [`DtErrKind::MismatchedLiteral`] — A literal character in the format string
217    ///   did not match the input.
218    /// - Name errors: [`DtErrKind::InvalidMonthName`], [`DtErrKind::InvalidWeekdayName`],
219    ///   [`DtErrKind::InvalidMeridiem`].
220    ///
221    /// ### Timezone and Offset errors
222    ///
223    /// - [`DtErrKind::OffsetMissingSign`] — A timezone offset (`%z` / `%Q`) did not
224    ///   start with `+` or `-`.
225    /// - [`DtErrKind::InvalidOffsetHour`] — Invalid hour value in a timezone offset.
226    /// - [`DtErrKind::InvalidOffsetMinute`] — Invalid minute value in a timezone offset.
227    /// - [`DtErrKind::InvalidOffsetSecond`] — Invalid second value in a timezone offset.
228    /// - [`DtErrKind::InvalidOffsetColons`] — Incorrect number of colons or missing
229    ///   required colon in a timezone offset.
230    /// - [`DtErrKind::InvalidOffset`] — General failure while parsing a numeric
231    ///   timezone offset.
232    /// - [`DtErrKind::InvalidTimeZone`] — Invalid or unparseable IANA timezone name
233    ///   (used by the `%Q` directive).
234    ///
235    /// ### Post-processing / validation errors
236    ///
237    /// - [`DtErrKind::TrailingCharacters`] — The input contained trailing characters
238    ///   after parsing and `fmt_can_end_before_inp` was `false`.
239    /// - [`DtErrKind::Incomplete`] — Required date components (month or day) were
240    ///   missing and `allow_partial_date` was `false`.
241    ///
242    /// ### Conversion to [`Dt`] errors
243    ///
244    /// These errors can occur *after* successful parsing, inside [`Parts::to_dt`]:
245    ///
246    /// - [`DtErrKind::InvalidDate`] or [`DtErrKind::InvalidInput`] — Unable to
247    ///   construct a valid date from the parsed components.
248    /// - Out-of-range or conflicting field errors (e.g. [`DtErrKind::DayOfYearOutOfRange`],
249    ///   [`DtErrKind::IsoWeekOutOfRange`], [`DtErrKind::WeekOutOfRange`], etc.).
250    /// - [`DtErrKind::InvalidItem`] — ISO week 53 requested for a year that does not
251    ///   contain 53 ISO weeks.
252    /// - Feature-dependent errors (when `jiff-tz` is involved):
253    ///   - [`DtErrKind::InvalidTimeZone`], [`DtErrKind::InvalidNumber`],
254    ///     [`DtErrKind::InvalidBytes`].
255    ///
256    /// The error kind is available via [`DtErr::kind()`].
257    #[inline(always)]
258    pub fn from_str(
259        s: &str,
260        fmt: &str,
261        inp_can_end_before_fmt: bool,
262        fmt_can_end_before_inp: bool,
263        allow_partial_date: bool,
264    ) -> Result<Dt, DtErr> {
265        Parts::from_str(
266            fmt,
267            s,
268            inp_can_end_before_fmt,
269            fmt_can_end_before_inp,
270            allow_partial_date,
271        )?
272        .to_dt()
273    }
274
275    /// Parses and validates a `strptime`-style format string into a reusable [`StrPTimeFmt`].
276    ///
277    /// The format is checked once for syntax errors and unsupported directives,
278    /// then stored in a compact fixed-size buffer. The resulting `StrPTimeFmt` is
279    /// can be used repeatedly with
280    /// [`StrPTimeFmt::to_dt`](../struct.StrPTimeFmt.html#method.to_dt)
281    /// and
282    /// [`StrPTimeFmt::to_str`](../struct.StrPTimeFmt.html#method.to_str)
283    /// without re-validating.
284    ///
285    /// - This unfortunately doesn't improve parsing performance.
286    /// - Only ASCII formats up to
287    ///   [`StrPTimeFmt::MAX_FMT_LEN`](../struct.StrPTimeFmt.html#associatedconstant.MAX_FMT_LEN)
288    ///   bytes are accepted.
289    ///
290    /// ## Parameters
291    ///
292    /// - `strptime_fmt`: The format string using `%` directives (e.g. `"%Y-%m-%d %H:%M:%S"`,
293    ///   `"%F %T"`, `"%Y-%m-%dT%H:%M:%S%.3fZ"`).
294    ///
295    /// ## Errors
296    ///
297    /// Returns [`DtErr`] if the format is:
298    /// - Longer than
299    ///   [`StrPTimeFmt::MAX_FMT_LEN`](../struct.StrPTimeFmt.html#associatedconstant.MAX_FMT_LEN)
300    ///   bytes.
301    /// - Not valid ASCII.
302    /// - Contains unknown, unsupported, or malformed directives.
303    #[inline(always)]
304    pub fn parse_fmt(strptime_fmt: &str) -> Result<StrPTimeFmt, DtErr> {
305        StrPTimeFmt::new(strptime_fmt)
306    }
307
308    /// Generalized no alloc parser.
309    ///
310    /// - Only supports ASCII characters.
311    /// - This function is considerably faster than all other string parsing methods if
312    ///   your date-time string is in one of the supported formats.
313    /// - Timezones beyond UTC aliases require the `jiff-tz` feature, which requires `std`.
314    ///
315    /// ## Returns
316    ///
317    /// - If there is NOT a trailing time scale in the input and the format of the input
318    ///   is a typical datetime iso e.g. `2000-01-01T17:00:00` then the time scale is
319    ///   assumed to be `UTC` and the [`Dt`] goes through a `UTC` -> `TAI` conversion
320    ///   (adding leap seconds).
321    /// - If there is NOT a trailing time scale in the input and the format of the input
322    ///   is a seconds count, jd, or mjd then the time scale is assumed to be `TAI` and
323    ///   no conversion happens.
324    /// - If there IS a trailing time scale in the input then the input goes through
325    ///   a time scale conversion (regardless of input format) of the provided time
326    ///   scale -> `TAI`. If the trailing time scale is `TAI` then no conversion occurs.
327    ///
328    /// A [`Dt`] of the `TAI` time scale is returned.
329    ///
330    /// ## Supported formats
331    ///
332    /// An **optional** library time scale right on the end of the input, e.g. `TAI` is
333    /// supported for all of the below formats.
334    ///
335    /// ### ISO
336    ///
337    /// #### Format examples:
338    ///
339    /// - **`+2000-01-01T17:00:00 -0500 [America/New_York] TAI`**.
340    /// - **`2024 Apr 18, 14:30:25 [America/New_York]`**. Abbreviated or full month
341    /// - **`2024-109 14:30:25 [America/New_York]`**. Day of year
342    ///
343    /// #### Notes:
344    ///
345    /// - If a time is included then some kind of date-time separator e.g. `T` or space is
346    ///   required.
347    /// - Supports both calendar (`%Y-%m-%d`) and day-of-year (`%Y-%j`) formats.
348    /// - Treats years digits literally as shown, for example `99-01-01` would be
349    ///   the year 99 AD not 1999.
350    /// - Supported **optional** components:
351    ///     - Time components after a date e.g. `T12:00:00`.
352    ///     - Offset after time components or directly after the date e.g. `+0200` or
353    ///       `2023-01-01+05:00`.
354    ///     - Timezone name, **requires square brackets** and **requires `jiff-tz`**
355    ///       feature, after time or offset e.g. `T12:00:00 [America/New_York]`.
356    ///
357    /// ### Seconds since J2000 Noon
358    ///
359    /// #### Format examples:
360    ///
361    /// - **`SEC 1234.567 TDB`**.
362    ///
363    /// #### Notes:
364    ///
365    /// - `sec` prefix is required but case-**in**sensitive.
366    /// - Fractional seconds are optional.
367    ///
368    /// ### JD
369    ///
370    /// #### Format examples:
371    ///
372    /// - **`JD 2451545.0 TAI`**.
373    ///
374    /// #### Notes:
375    ///
376    /// - `jd` prefix is required but case-**in**sensitive.
377    /// - Fractional days are optional.
378    ///
379    /// ### MJD
380    ///
381    /// #### Format examples:
382    ///
383    /// - **`MJD 51544.5 TT`**.
384    ///
385    /// #### Notes:
386    ///
387    /// - `mjd` prefix is required but case-**in**sensitive.
388    /// - Fractional days are optional.
389    ///
390    /// ## See also
391    ///
392    /// - [`Parts::from_str_iso`](../struct.Parts.html#method.from_str_iso)
393    #[inline(always)]
394    pub fn from_str_iso(s: &str) -> Result<Self, DtErr> {
395        Parts::from_str_iso(s)?.to_dt()
396    }
397
398    /// Parses a decimal seconds string (with optional fractional part) as seconds
399    /// since
400    /// [`Dt::ZERO`](../struct.Dt.html#associatedconstant.ZERO)
401    /// on the chosen time scale.
402    ///
403    /// The returned [`Dt`] is on the `TAI` time [`Scale`], having been converted
404    /// to `TAI` from whatever the **trailing** scale is, or if no scale is provided
405    /// then no conversion takes place.
406    ///
407    /// Leading non-numeric characters are skipped until a number start is found
408    /// (`+`, `-`, `.`, or digit).
409    ///
410    /// - Fractional seconds are limited to the first 18 digits (attosecond
411    ///   precision); extra digits are truncated.
412    /// - Oversized integer parts saturate instead of failing.
413    /// - Inputs longer than [`STRTIME_SIZE`](../constants/constant.STRTIME_SIZE.html) are rejected.
414    /// - Returns `None` only for completely unparseable input (empty, sign/dot
415    ///   only, no digits after skipping, etc.).
416    ///
417    /// ## Examples
418    ///
419    /// ```rust
420    /// use deep_time::{Dt, Scale};
421    ///
422    /// let d = Dt::from_str_sec_f("1700000000.123456789012345678", Some(Scale::TAI)).unwrap();
423    /// assert_eq!(d.to_sec64(), 1700000000);
424    ///
425    /// // Leading junk is skipped
426    /// let d = Dt::from_str_sec_f("ts= -0.00123 suffix", Some(Scale::TAI)).unwrap();
427    /// assert!(d.to_attos() < 0);
428    ///
429    /// // Pure negative fraction
430    /// let d = Dt::from_str_sec_f("-.5", Some(Scale::TT)).unwrap();
431    /// assert!(d.to_attos() < 0);
432    ///
433    /// // Scale parsed from trailing abbreviation when passing None
434    /// let d = Dt::from_str_sec_f("42.75 GPS", None).unwrap();
435    /// assert_eq!(d.target, Scale::GPS);
436    ///
437    /// // 1 attosecond
438    /// let d = Dt::from_str_sec_f("0.000000000000000001", Some(Scale::TAI)).unwrap();
439    /// assert_eq!(d.to_attos() % 1_000_000_000_000_000_000, 1);
440    /// ```
441    pub fn from_str_sec_f(s: &str, scale: Option<Scale>) -> Option<Dt> {
442        let parsed = Parts::parse_str_f(s.as_bytes(), scale)?;
443
444        let int_attos = (parsed.int_u as i128) * ATTOS_PER_SEC_I128;
445        let signed_attos = if parsed.negative {
446            -int_attos - (parsed.frac_attos as i128)
447        } else {
448            int_attos + (parsed.frac_attos as i128)
449        };
450
451        Some(Dt::from_attos(signed_attos, parsed.scale))
452    }
453
454    /// Parses a decimal Julian Date string (with optional fractional part).
455    ///
456    /// The returned [`Dt`] is on the `TAI` time [`Scale`], having been converted
457    /// to `TAI` from whatever the **trailing** scale is, or if no scale is provided
458    /// then no conversion takes place.
459    ///
460    /// Leading junk is skipped the same way as [`Dt::from_str_sec_f`].
461    /// Fractional day precision up to 18 digits.
462    ///
463    /// Returns `None` for unparseable input.
464    ///
465    /// JD 2451545.0 is the library epoch (2000-01-01 noon).
466    ///
467    /// ## Examples
468    ///
469    /// ```rust
470    /// use deep_time::{Dt, Scale};
471    ///
472    /// let d = Dt::from_str_jd_f("2451545.0", Some(Scale::TAI)).unwrap();
473    /// assert_eq!(d.to_jd(), (2_451_545, 0));
474    ///
475    /// let d = Dt::from_str_jd_f("2451545.25 TT", None).unwrap();
476    /// assert_eq!(d.target, Scale::TT);
477    ///
478    /// let d = Dt::from_str_jd_f("2451544.5", Some(Scale::TAI)).unwrap();
479    /// assert!(d.to_attos() < 0);
480    /// ```
481    pub fn from_str_jd_f(s: &str, scale: Option<Scale>) -> Option<Dt> {
482        Parts::from_str_jd_f(s, scale).and_then(|p| p.to_dt().ok())
483    }
484
485    /// Parses a decimal Modified Julian Date string (with optional fractional part).
486    ///
487    /// The returned [`Dt`] is on the `TAI` time [`Scale`], having been converted
488    /// to `TAI` from whatever the **trailing** scale is, or if no scale is provided
489    /// then no conversion takes place.
490    ///
491    /// Leading junk is skipped the same way as [`Dt::from_str_sec_f`].
492    /// Fractional day precision up to 18 digits.
493    ///
494    /// Returns `None` for unparseable input.
495    ///
496    /// MJD 51544.5 is the library epoch (2000-01-01 noon).
497    ///
498    /// ## Examples
499    ///
500    /// ```rust
501    /// use deep_time::{Dt, Scale};
502    ///
503    /// let d = Dt::from_str_mjd_f("51544.5", Some(Scale::TAI)).unwrap();
504    /// assert_eq!(d.to_jd(), (2_451_545, 0));
505    ///
506    /// let d = Dt::from_str_mjd_f("51544.25 TT", None).unwrap();
507    /// assert_eq!(d.target, Scale::TT);
508    ///
509    /// let d = Dt::from_str_mjd_f("51543.5", Some(Scale::TAI)).unwrap();
510    /// assert!(d.to_attos() < 0);
511    /// ```
512    pub fn from_str_mjd_f(s: &str, scale: Option<Scale>) -> Option<Dt> {
513        Parts::from_str_mjd_f(s, scale).and_then(|p| p.to_dt().ok())
514    }
515
516    /// Parses an ISO 8601 duration string into a [`Dt`] representing a pure time interval.
517    ///
518    /// Supports the full `PnYnMnDTnHnMnS` format (case-insensitive), including:
519    /// - Optional leading `+` or `-` sign
520    /// - `P` / `p` prefix (required)
521    /// - Optional `T` / `t` separator between date and time parts
522    /// - Weeks (`W` / `w`)
523    /// - Fractional seconds with up to 9 digits of precision (nanosecond resolution;
524    ///   the parsed value is scaled to attosecond resolution in the resulting [`Dt`]).
525    ///
526    /// The returned [`Dt`] is a **duration** (signed interval) on the TAI scale.
527    /// It can be added to/subtracted from other `Dt` values, multiplied/divided,
528    /// rounded, etc.
529    ///
530    /// ## Not Reference-Time Aware
531    ///
532    /// This parser is **not reference-time aware**. Calendar units (`Y`, `M`) are
533    /// converted to a fixed number of seconds using standard average lengths
534    /// rather than being resolved against a specific date. This makes parsing
535    /// fast and allocation-free, but `P1M` always represents exactly the same
536    /// duration regardless of context.
537    ///
538    /// ## Parameters
539    ///
540    /// - `s`: The ISO 8601 duration string (e.g. `"P1Y2M3DT4H5M6.123456789012345678S"`,
541    ///   `"-PT30M"`, `"P7W"`, `"+P1DT12H"`).
542    ///
543    /// ## Errors
544    ///
545    /// Returns a [`DtErr`] if parsing fails. The error kind is available via
546    /// [`DtErr::kind()`].
547    ///
548    /// ### Input / structure errors
549    ///
550    /// - [`DtErrKind::Empty`] — The input string is empty.
551    /// - [`DtErrKind::MustStartWith`] — Missing `P` / `p` prefix (after optional leading sign).
552    /// - [`DtErrKind::InvalidSyntax`] — Invalid syntax, e.g. `T` with no following time part,
553    ///   or more than one `T`/`t` separator.
554    /// - [`DtErrKind::TrailingCharacters`] — Additional components appear after a fractional
555    ///   seconds value (only the final `S` component may carry a fraction).
556    ///
557    /// ### Component parsing errors
558    ///
559    /// - [`DtErrKind::ExpectedValue`] — Expected a numeric value for a component but found none.
560    /// - [`DtErrKind::ExpectedFractional`] — A `.` or `,` was present for a fractional part
561    ///   but no digits followed.
562    /// - [`DtErrKind::ExpectedUnit`] — A number was parsed but no unit designator
563    ///   (`Y`/`M`/`W`/`D`/`H`/`S` etc.) followed it.
564    /// - [`DtErrKind::InvalidNumber`] — A numeric component could not be parsed as an `i64`
565    ///   (typically too large).
566    /// - [`DtErrKind::InvalidBytes`] — Internal UTF-8 conversion failure while reading a number
567    ///   (should not occur for valid ASCII input).
568    /// - [`DtErrKind::InvalidFractional`] — The fractional part digits could not be parsed as an integer.
569    /// - [`DtErrKind::FracOutOfRange`] — More than 9 digits were supplied for fractional seconds.
570    /// - [`DtErrKind::InvalidItem`] — A fractional part was supplied on a unit other than seconds.
571    ///
572    /// ### Unit and range errors
573    ///
574    /// - [`DtErrKind::UnknownItem`] — An unknown unit designator character was used.
575    /// - [`DtErrKind::YearOutOfRange`], [`DtErrKind::MonthOutOfRange`],
576    ///   [`DtErrKind::WeekOutOfRange`], [`DtErrKind::DayOutOfRange`] — The component value
577    ///   (after sign) overflows when multiplied by the corresponding fixed-length constant
578    ///   (checked arithmetic).
579    pub fn from_iso_duration(s: &str) -> Result<Dt, DtErr> {
580        let len = s.len();
581        if len == 0 {
582            return Err(an_err!(DtErrKind::Empty));
583        }
584
585        let b = s.as_bytes();
586        let mut i = 0usize;
587
588        // Optional leading sign (+ or -)
589        let mut sign: i64 = 1;
590        if i < len && matches!(b[i], b'+' | b'-') {
591            if b[i] == b'-' {
592                sign = -1;
593            }
594            i += 1;
595        }
596
597        // Must start with P/p
598        if i >= len || !matches!(b[i], b'P' | b'p') {
599            return Err(an_err!(DtErrKind::MustStartWith));
600        }
601        i += 1;
602
603        // Find the (single) T/t separator
604        let t_pos = b[i..]
605            .iter()
606            .position(|&c| matches!(c, b'T' | b't'))
607            .map(|p| i + p);
608
609        let (date_part, time_part) = match t_pos {
610            Some(pos) => {
611                if pos == len - 1 {
612                    return Err(an_err!(DtErrKind::InvalidSyntax));
613                }
614                if b[pos + 1..].iter().any(|&c| matches!(c, b'T' | b't')) {
615                    return Err(an_err!(DtErrKind::InvalidSyntax));
616                }
617                (&b[i..pos], &b[pos + 1..])
618            }
619            None => (&b[i..], &[] as &[u8]),
620        };
621
622        let mut has_fraction = false;
623        let mut total_nanos: i128 = 0;
624
625        // Both date and time parts now use the same fixed-length logic
626        Self::parse_duration_part(date_part, &mut total_nanos, true, sign, &mut has_fraction)?;
627        Self::parse_duration_part(time_part, &mut total_nanos, false, sign, &mut has_fraction)?;
628
629        // Convert accumulated nanoseconds to attoseconds and build Dt
630        let total_attos = total_nanos * 1_000_000_000i128;
631        Ok(Dt::span(total_attos))
632    }
633
634    /// Parses a single component (number + optional fraction + unit) from the slice,
635    /// advancing the index `i`. Returns `None` when the slice is exhausted.
636    fn parse_next_component(
637        chars: &[u8],
638        i: &mut usize,
639        sign: i64,
640        has_fraction: &mut bool,
641    ) -> Result<Option<ParsedComponent>, DtErr> {
642        if *i >= chars.len() {
643            return Ok(None);
644        }
645
646        if *has_fraction {
647            return Err(an_err!(DtErrKind::TrailingCharacters));
648        }
649
650        // Parse integer part
651        let start = *i;
652        while *i < chars.len() && chars[*i].is_ascii_digit() {
653            *i += 1;
654        }
655        if start == *i {
656            return Err(an_err!(DtErrKind::ExpectedValue));
657        }
658
659        let int_str = core::str::from_utf8(&chars[start..*i])
660            .map_err(|e| an_err!(DtErrKind::InvalidBytes, "{}", e))?;
661        let int: i64 = int_str.parse().map_err(|e: core::num::ParseIntError| {
662            an_err!(DtErrKind::InvalidNumber, "{}: {}", int_str, e)
663        })?;
664
665        // Parse optional fraction
666        let mut frac_num: i64 = 0;
667        let mut frac_digits: usize = 0;
668        if *i < chars.len() && matches!(chars[*i], b'.' | b',') {
669            *i += 1;
670            let frac_start = *i;
671            while *i < chars.len() && chars[*i].is_ascii_digit() {
672                *i += 1;
673            }
674            frac_digits = *i - frac_start;
675            if frac_digits == 0 {
676                return Err(an_err!(DtErrKind::ExpectedFractional));
677            }
678            if frac_digits > 9 {
679                return Err(an_err!(DtErrKind::FracOutOfRange));
680            }
681
682            let frac_str = core::str::from_utf8(&chars[frac_start..*i])
683                .map_err(|e| an_err!(DtErrKind::InvalidBytes, "{}", e))?;
684            frac_num = frac_str.parse().map_err(|e: core::num::ParseIntError| {
685                an_err!(DtErrKind::InvalidFractional, "{}: {}", frac_str, e)
686            })?;
687        }
688
689        // Unit must follow
690        if *i >= chars.len() {
691            return Err(an_err!(DtErrKind::ExpectedUnit));
692        }
693        let unit = chars[*i];
694        *i += 1;
695
696        // Only seconds support a fractional part
697        if frac_digits > 0 {
698            if !matches!(unit, b'S' | b's') {
699                return Err(an_err!(DtErrKind::InvalidItem));
700            }
701            *has_fraction = true;
702        }
703
704        let signed_int = (int as i128 * sign as i128) as i64;
705
706        Ok(Some(ParsedComponent {
707            unit,
708            signed_int,
709            frac_digits,
710            frac_num,
711        }))
712    }
713
714    /// Helper that parses **one section** of an ISO duration (date or time part)
715    /// and accumulates nanoseconds into `total_nanos`.
716    ///
717    /// Years, months, weeks, and days are converted using the fixed-length
718    /// constants (the only sensible semantics for a pure `Dt`).
719    fn parse_duration_part(
720        chars: &[u8],
721        total_nanos: &mut i128,
722        is_date: bool,
723        sign: i64,
724        has_fraction: &mut bool,
725    ) -> Result<(), DtErr> {
726        let mut i = 0;
727        while let Some(comp) = Self::parse_next_component(chars, &mut i, sign, has_fraction)? {
728            let contrib_nanos = match (is_date, comp.unit) {
729                (true, b'Y' | b'y') => {
730                    let total_secs = (comp.signed_int as i128)
731                        .checked_mul(SEC_PER_YEAR)
732                        .ok_or_else(|| an_err!(DtErrKind::YearOutOfRange))?;
733                    total_secs * 1_000_000_000i128
734                }
735                (true, b'M' | b'm') => {
736                    let total_secs = (comp.signed_int as i128)
737                        .checked_mul(SEC_PER_MONTH)
738                        .ok_or_else(|| an_err!(DtErrKind::MonthOutOfRange))?;
739                    total_secs * 1_000_000_000i128
740                }
741                (true, b'W' | b'w') => {
742                    let total_secs = (comp.signed_int as i128)
743                        .checked_mul(SEC_PER_WEEK as i128)
744                        .ok_or_else(|| an_err!(DtErrKind::WeekOutOfRange))?;
745                    total_secs * 1_000_000_000i128
746                }
747                (true, b'D' | b'd') => {
748                    let total_secs = (comp.signed_int as i128)
749                        .checked_mul(SEC_PER_DAY)
750                        .ok_or_else(|| an_err!(DtErrKind::DayOutOfRange))?;
751                    total_secs * 1_000_000_000i128
752                }
753                (false, b'H' | b'h') => (comp.signed_int as i128) * 3_600_000_000_000i128,
754                (false, b'M' | b'm') => (comp.signed_int as i128) * 60_000_000_000i128,
755                (false, b'S' | b's') => {
756                    let mut sec_nanos = (comp.signed_int as i128) * 1_000_000_000i128;
757                    if comp.frac_digits > 0 {
758                        let frac_ns = (comp.frac_num as i128 * sign as i128 * 1_000_000_000i128)
759                            / 10i128.pow(comp.frac_digits as u32);
760                        sec_nanos += frac_ns;
761                    }
762                    sec_nanos
763                }
764                _ => {
765                    return Err(an_err!(DtErrKind::UnknownItem, "{}", comp.unit as char));
766                }
767            };
768
769            *total_nanos = total_nanos.saturating_add(contrib_nanos);
770        }
771        Ok(())
772    }
773
774    /// Parses a media-style duration string.
775    ///
776    /// Accepts formats like:
777    /// - `"0:45"`, `"9:41"`
778    /// - `"1:23:45"`
779    /// - `"1:07:54:30"`
780    /// - `"-1:23:45"`
781    ///
782    /// ## Errors
783    ///
784    /// Returns a [`DtErr`] if the input cannot be parsed as a valid media-style
785    /// duration. The error kind is available via [`DtErr::kind`].
786    ///
787    /// This function uses saturating arithmetic, so it never returns range or
788    /// overflow errors.
789    ///
790    /// ### Input / structure errors
791    ///
792    /// - [`DtErrKind::Empty`] — The string is empty or contains only ASCII whitespace.
793    /// - [`DtErrKind::InvalidInput`] — A single minus sign with nothing after it.
794    /// - [`DtErrKind::InvalidSyntax`] — The input does not contain exactly 2, 3, or 4
795    ///   colon-separated numeric components.
796    /// - [`DtErrKind::TrailingCharacters`] — Non-whitespace characters remain after
797    ///   the final numeric component.
798    ///
799    /// ### Parsing errors
800    ///
801    /// - [`DtErrKind::ExpectedValue`] — A component was expected to begin with a digit
802    ///   (either at the start of the string or immediately after a `:`) but did not.
803    ///
804    /// ## See also
805    ///
806    /// - [`Dt::to_str_media_duration`](../struct.Dt.html#method.to_str_media_duration)
807    /// - [`Dt::to_str_lite_media_duration`](../struct.Dt.html#method.to_str_lite_media_duration)
808    pub fn from_str_media_duration(input: &str) -> Result<Dt, DtErr> {
809        let bytes = input.as_bytes();
810        let len = bytes.len();
811        let mut pos: usize = 0;
812
813        // Skip leading whitespace
814        while pos < len && bytes[pos].is_ascii_whitespace() {
815            pos += 1;
816        }
817
818        if pos == len {
819            return Err(an_err!(DtErrKind::Empty));
820        }
821
822        // Optional single leading minus
823        let negative = if bytes[pos] == b'-' {
824            pos += 1;
825            if pos == len {
826                return Err(an_err!(DtErrKind::InvalidInput));
827            }
828            true
829        } else {
830            false
831        };
832
833        // Parse up to 4 numeric components separated by ':'
834        let mut components: [i128; 4] = [0; 4];
835        let mut count: usize = 0;
836
837        loop {
838            if count >= 4 {
839                break;
840            }
841
842            // Parse one number
843            if pos >= len || !bytes[pos].is_ascii_digit() {
844                return Err(an_err!(DtErrKind::ExpectedValue));
845            }
846
847            let mut value: i128 = 0;
848            while pos < len && bytes[pos].is_ascii_digit() {
849                value = value
850                    .saturating_mul(10)
851                    .saturating_add((bytes[pos] - b'0') as i128);
852                pos += 1;
853            }
854
855            components[count] = value;
856            count += 1;
857
858            // Check for more components
859            if pos >= len || bytes[pos] != b':' {
860                break;
861            }
862
863            pos += 1; // consume ':'
864
865            // Reject trailing ':' with no number after it
866            if pos >= len || !bytes[pos].is_ascii_digit() {
867                return Err(an_err!(DtErrKind::ExpectedValue));
868            }
869        }
870
871        if !(2..=4).contains(&count) {
872            return Err(an_err!(DtErrKind::InvalidSyntax));
873        }
874
875        // Skip trailing whitespace
876        while pos < len && bytes[pos].is_ascii_whitespace() {
877            pos += 1;
878        }
879
880        if pos != len {
881            return Err(an_err!(DtErrKind::TrailingCharacters));
882        }
883
884        // Convert to total seconds
885        let total_secs: i128 = match count {
886            2 => components[0] * 60 + components[1], // M:SS
887            3 => components[0] * 3600 + components[1] * 60 + components[2], // H:MM:SS
888            4 => components[0] * 86400 + components[1] * 3600 + components[2] * 60 + components[3], // D:H:MM:SS
889            _ => unreachable!(),
890        };
891
892        let total_secs = if negative { -total_secs } else { total_secs };
893        let attos = total_secs.saturating_mul(ATTOS_PER_SEC_I128);
894
895        Ok(Dt::span(attos))
896    }
897}