Skip to main content

deep_time/dt/
from_str.rs

1use crate::{
2    ATTOS_PER_NS_I128, ATTOS_PER_SEC_I128, Dt, DtErr, DtErrKind, Parts, SEC_PER_DAY, SEC_PER_MONTH,
3    SEC_PER_WEEK, SEC_PER_YEAR, Scale, an_err, dt, sec,
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(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`](../struct.Dt.html#method.from_str)).
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`](../struct.Dt.html#method.from_str)
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(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_strptime(
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_strptime(
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    /// Fast, no-alloc parser for common ISO-like and epoch-style date-time strings.
276    ///
277    /// Equivalent to [`Parts::from_str`](../civil_parts/struct.Parts.html#method.from_str)
278    /// followed by [`Parts::to_dt`](../civil_parts/struct.Parts.html#method.to_dt). The
279    /// formats and lenience rules below are those of the `Parts` parser; this method
280    /// then resolves components to a single instant.
281    ///
282    /// - Only **ASCII** input is supported.
283    /// - Inputs longer than [`STRTIME_SIZE`](../consts/constant.STRTIME_SIZE.html) are
284    ///   rejected with [`DtErrKind::InvalidLen`](../error/enum.DtErrKind.html#variant.InvalidLen).
285    /// - Leading non-date junk is skipped until a year-like start (`digit` or `±`digit),
286    ///   a recognized alphabetic prefix (`JD` / `MJD` / `SEC`, case-insensitive), or an
287    ///   English weekday name / abbrev (day-month-year order).
288    /// - Trailing characters after a successful parse are generally ignored (lenient).
289    /// - Considerably faster than format-string / smart parsers when the input is one
290    ///   of the shapes below.
291    /// - Timezones beyond UTC aliases require the `jiff-tz` or `jiff-tz-bundle` feature
292    ///   (both require `alloc`).
293    ///
294    /// ## Returns
295    ///
296    /// Always a [`Dt`] on the **`TAI`** time scale (after any conversion).
297    ///
298    /// - No trailing scale + civil ISO-like input (calendar / DOY / ISO week) → interpret
299    ///   as **UTC**, then convert **UTC → TAI** (leap seconds applied).
300    /// - No trailing scale + `SEC` / `JD` / `MJD` → interpret as **TAI** (no conversion).
301    /// - Trailing scale present (e.g. `TDB`, `GPS`) → convert **that scale → TAI**
302    ///   (no-op if the scale is already `TAI`).
303    ///
304    /// The returned value’s `target` reflects the scale assumed before conversion to TAI.
305    ///
306    /// ## Supported formats
307    ///
308    /// An **optional** library time scale at the end of the input (e.g. `TAI`) is
309    /// supported for all of the formats below.
310    ///
311    /// ### ISO-like civil date-times
312    ///
313    /// #### Format examples
314    ///
315    /// - **`+2000-01-01T17:00:00 -0500 [America/New_York] TAI`**
316    /// - **`2024 Apr 18, 14:30:25 [America/New_York]`** — month abbrev or full English name
317    /// - **`Sat, 07 Feb 2015 11:22:33`**, **`Sat,07Feb2015T11:22:33`** — weekday first
318    ///   (day-month-year; `Sun`…`Sat` or full English name)
319    /// - **`2024-109 14:30:25`** — day of year (`%Y-%j`)
320    /// - **`2024-W11`**, **`2024W11`**, **`2024-W11-4`** — ISO week date (`%G-W%V`, optional
321    ///   weekday `%u` with Monday=`1` … Sunday=`7`)
322    /// - **`2024`**, **`2024-03`**, **`2024 Mar`** — partial dates (missing month/day → `1`)
323    /// - **`2024-04-18T9:3:5.5`**, **`2024-04-18T143025`** — flexible / compact time
324    ///
325    /// #### Date forms
326    ///
327    /// Year digits are taken **literally** (no century window): `99-01-01` is year 99 AD.
328    /// Year overflow during accumulation yields
329    /// [`DtErrKind::YearOutOfRange`](../error/enum.DtErrKind.html#variant.YearOutOfRange).
330    ///
331    /// **Weekday first** → day, month, year (required). Hyphen before the year is a
332    /// separator (`07-Feb-2015`); a signed year needs space or a doubled sign
333    /// (`07 Feb -4714`, `07-Feb--4714`, `+2015`).
334    ///
335    /// **Otherwise year first.** After an optional sign and year digits, exactly one of:
336    ///
337    /// 1. **ISO week** — `W`/`w` immediately after the year (or after a non-letter
338    ///    separator such as `-`): e.g. `2024-W11`, `2024W114`.
339    ///    - Week number required right after `W` (1–2 digits); `0` becomes week `1`.
340    ///    - Optional weekday: `-4` or basic trailing digit `1..=7` (Monday=`1` … Sunday=`7`);
341    ///      if omitted, Monday is used when resolving the instant.
342    ///    - This is **not** strftime `%W` (Monday week-of-year on a calendar year).
343    /// 2. **Day of year** — three slots `[digit|space][digit|space][digit]` not followed
344    ///    by another digit (so `2024-0401` is calendar `04-01`, not DOY). Space padding
345    ///    is allowed (`2024-  9`).
346    /// 3. **Calendar month/day** — numeric month (1–2 digits) or English month name
347    ///    (abbrev or full; matched from the first three letters), then day (1–2 digits).
348    ///
349    /// **Partial calendar dates** (year-first only) default missing fields to `1`
350    /// (January / day 1):
351    ///
352    /// - Year only: `2024`, `2024-` → 1 January.
353    /// - Year-month: `2024-03`, `2024 Mar` → day 1.
354    /// - Explicit zero month/day digits are treated like omitted (`2024-00`, `2024-03-0` → 1).
355    /// - Year or year-month may be followed by time: `2024T12:00`, `2024-03T12:00`.
356    ///
357    /// #### Time (optional)
358    ///
359    /// - Usually introduced by `T`/`t`, space, or another non-digit separator; compact
360    ///   glued times after a full day are also accepted (e.g. `…18143025`).
361    /// - Hour, minute, and second are **1 or 2** digits when the field ends at `:` /
362    ///   space (or, for seconds, `.` before a fraction).
363    /// - Compact digit runs without separators are supported (e.g. `T143025`).
364    /// - Fractional seconds: `.` then digits (up to 18 kept as attoseconds; extra digits
365    ///   ignored).
366    /// - Optional trailing `Z`/`z` is consumed.
367    /// - Minutes must be `≤ 59`; seconds must be `≤ 60` (leap second `60` allowed; resolved
368    ///   by [`Parts::to_dt`](../civil_parts/struct.Parts.html#method.to_dt)).
369    ///
370    /// #### Optional trailing components
371    ///
372    /// - **Offset** — `+`/`-` then hours (and optional minutes), with or without `:`:
373    ///   `+02:00`, `-0530`, also allowed directly after the date.
374    /// - **IANA name** — must be in square brackets, e.g. `[America/New_York]`.
375    ///   Resolving non-UTC aliases requires the `jiff-tz` or `jiff-tz-bundle` feature
376    ///   (both require `alloc`).
377    /// - **Scale** — library abbreviation, e.g. `TAI`, `UTC`, `TDB`, `GPS`.
378    ///
379    /// ### Seconds since 2000-01-01 noon (library epoch)
380    ///
381    /// #### Format examples
382    ///
383    /// - **`SEC 1234.567 TDB`**
384    /// - **`sec1234.5 TAI`**
385    ///
386    /// #### Notes
387    ///
388    /// - `sec` prefix is required (case-insensitive).
389    /// - Fractional seconds optional.
390    ///
391    /// ### Julian Date
392    ///
393    /// #### Format examples
394    ///
395    /// - **`JD 2451545.0 TAI`**
396    /// - **`JD2451545.25 TT`**
397    ///
398    /// #### Notes
399    ///
400    /// - `jd` prefix is required (case-insensitive).
401    /// - Fractional days optional.
402    ///
403    /// ### Modified Julian Date
404    ///
405    /// #### Format examples
406    ///
407    /// - **`MJD 51544.5 TT`**
408    /// - **`mjd 51544.25`**
409    ///
410    /// #### Notes
411    ///
412    /// - `mjd` prefix is required (case-insensitive).
413    /// - Fractional days optional.
414    ///
415    /// ## See also
416    ///
417    /// - [`Parts::from_str`](../civil_parts/struct.Parts.html#method.from_str) —
418    ///   same string parse without resolving to a [`Dt`].
419    #[allow(clippy::should_implement_trait)]
420    #[inline(always)]
421    pub fn from_str(s: &str) -> Result<Self, DtErr> {
422        Parts::from_str(s)?.to_dt()
423    }
424
425    /// Parses a decimal seconds string (with optional fractional part) as seconds
426    /// since
427    /// [`Dt::ZERO`](../struct.Dt.html#associatedconstant.ZERO)
428    /// on the chosen time scale.
429    ///
430    /// The returned [`Dt`] is on the `TAI` time [`Scale`], having been converted
431    /// to `TAI` from whatever the **trailing** scale is, or if no scale is provided
432    /// then no conversion takes place.
433    ///
434    /// Leading non-numeric characters are skipped until a number start is found
435    /// (`+`, `-`, `.`, or digit).
436    ///
437    /// - Fractional seconds are limited to the first 18 digits (attosecond
438    ///   precision); extra digits are truncated.
439    /// - Oversized integer parts saturate instead of failing.
440    /// - Inputs longer than [`STRTIME_SIZE`](../consts/constant.STRTIME_SIZE.html) are rejected.
441    /// - Returns `None` only for completely unparseable input (empty, sign/dot
442    ///   only, no digits after skipping, etc.).
443    ///
444    /// ## Examples
445    ///
446    /// ```rust
447    /// use deep_time::{Dt, Scale};
448    ///
449    /// let d = Dt::from_str_sec_f("1700000000.123456789012345678", Some(Scale::TAI)).unwrap();
450    /// assert_eq!(d.to_sec64_floor(), 1700000000);
451    ///
452    /// // Leading junk is skipped
453    /// let d = Dt::from_str_sec_f("ts= -0.00123 suffix", Some(Scale::TAI)).unwrap();
454    /// assert!(d.to_attos() < 0);
455    ///
456    /// // Pure negative fraction
457    /// let d = Dt::from_str_sec_f("-.5", Some(Scale::TT)).unwrap();
458    /// assert!(d.to_attos() < 0);
459    ///
460    /// // Scale parsed from trailing abbreviation when passing None
461    /// let d = Dt::from_str_sec_f("42.75 GPS", None).unwrap();
462    /// assert_eq!(d.target, Scale::GPS);
463    ///
464    /// // 1 attosecond
465    /// let d = Dt::from_str_sec_f("0.000000000000000001", Some(Scale::TAI)).unwrap();
466    /// assert_eq!(d.to_attos() % 1_000_000_000_000_000_000, 1);
467    /// ```
468    #[inline]
469    pub fn from_str_sec_f(s: &str, scale: Option<Scale>) -> Option<Dt> {
470        Parts::from_str_sec_f(s, scale).and_then(|p| p.to_dt().ok())
471    }
472
473    /// Parses a decimal Julian Date string (with optional fractional part).
474    ///
475    /// The returned [`Dt`] is on the `TAI` time [`Scale`], having been converted
476    /// to `TAI` from whatever the **trailing** scale is, or if no scale is provided
477    /// then no conversion takes place.
478    ///
479    /// Leading junk is skipped the same way as [`Dt::from_str_sec_f`].
480    /// Fractional day precision up to 18 digits.
481    ///
482    /// Returns `None` for unparseable input.
483    ///
484    /// JD 2451545.0 is the library epoch (2000-01-01 noon).
485    ///
486    /// ## Examples
487    ///
488    /// ```rust
489    /// use deep_time::{Dt, Scale};
490    ///
491    /// let d = Dt::from_str_jd_f("2451545.0", Some(Scale::TAI)).unwrap();
492    /// assert_eq!(d.to_jd(), (2_451_545, 0));
493    ///
494    /// let d = Dt::from_str_jd_f("2451545.25 TT", None).unwrap();
495    /// assert_eq!(d.target, Scale::TT);
496    ///
497    /// let d = Dt::from_str_jd_f("2451544.5", Some(Scale::TAI)).unwrap();
498    /// assert!(d.to_attos() < 0);
499    /// ```
500    #[inline]
501    pub fn from_str_jd_f(s: &str, scale: Option<Scale>) -> Option<Dt> {
502        Parts::from_str_jd_f(s, scale).and_then(|p| p.to_dt().ok())
503    }
504
505    /// Parses a decimal Modified Julian Date string (with optional fractional part).
506    ///
507    /// The returned [`Dt`] is on the `TAI` time [`Scale`], having been converted
508    /// to `TAI` from whatever the **trailing** scale is, or if no scale is provided
509    /// then no conversion takes place.
510    ///
511    /// Leading junk is skipped the same way as [`Dt::from_str_sec_f`].
512    /// Fractional day precision up to 18 digits.
513    ///
514    /// Returns `None` for unparseable input.
515    ///
516    /// MJD 51544.5 is the library epoch (2000-01-01 noon).
517    ///
518    /// ## Examples
519    ///
520    /// ```rust
521    /// use deep_time::{Dt, Scale};
522    ///
523    /// let d = Dt::from_str_mjd_f("51544.5", Some(Scale::TAI)).unwrap();
524    /// assert_eq!(d.to_jd(), (2_451_545, 0));
525    ///
526    /// let d = Dt::from_str_mjd_f("51544.25 TT", None).unwrap();
527    /// assert_eq!(d.target, Scale::TT);
528    ///
529    /// let d = Dt::from_str_mjd_f("51543.5", Some(Scale::TAI)).unwrap();
530    /// assert!(d.to_attos() < 0);
531    /// ```
532    #[inline]
533    pub fn from_str_mjd_f(s: &str, scale: Option<Scale>) -> Option<Dt> {
534        Parts::from_str_mjd_f(s, scale).and_then(|p| p.to_dt().ok())
535    }
536
537    /// Parses an ISO 8601 duration string into a [`Dt`] representing a pure time interval.
538    ///
539    /// Supports the full `PnYnMnDTnHnMnS` format (case-insensitive), including:
540    /// - Optional leading `+` or `-` sign
541    /// - `P` / `p` prefix (required)
542    /// - Optional `T` / `t` separator between date and time parts
543    /// - Weeks (`W` / `w`)
544    /// - Fractional seconds with up to 9 digits of precision (nanosecond resolution;
545    ///   the parsed value is scaled to attosecond resolution in the resulting [`Dt`]).
546    ///
547    /// The returned [`Dt`] is a **duration** (signed interval) on the TAI scale.
548    /// It can be added to/subtracted from other `Dt` values, multiplied/divided,
549    /// rounded, etc.
550    ///
551    /// ## Not Reference-Time Aware
552    ///
553    /// This parser is **not reference-time aware**. Calendar units (`Y`, `M`) are
554    /// converted to a fixed number of seconds using standard average lengths
555    /// rather than being resolved against a specific date. This makes parsing
556    /// fast and allocation-free, but `P1M` always represents exactly the same
557    /// duration regardless of context.
558    ///
559    /// ## Parameters
560    ///
561    /// - `s`: The ISO 8601 duration string (e.g. `"P1Y2M3DT4H5M6.123456789012345678S"`,
562    ///   `"-PT30M"`, `"P7W"`, `"+P1DT12H"`).
563    ///
564    /// ## Errors
565    ///
566    /// Returns a [`DtErr`] if parsing fails. The error kind is available via
567    /// [`DtErr::kind()`].
568    ///
569    /// ### Input / structure errors
570    ///
571    /// - [`DtErrKind::Empty`] — The input string is empty.
572    /// - [`DtErrKind::MustStartWith`] — Missing `P` / `p` prefix (after optional leading sign).
573    /// - [`DtErrKind::InvalidSyntax`] — Invalid syntax, e.g. `T` with no following time part,
574    ///   or more than one `T`/`t` separator.
575    /// - [`DtErrKind::TrailingCharacters`] — Additional components appear after a fractional
576    ///   seconds value (only the final `S` component may carry a fraction).
577    ///
578    /// ### Component parsing errors
579    ///
580    /// - [`DtErrKind::ExpectedValue`] — Expected a numeric value for a component but found none.
581    /// - [`DtErrKind::ExpectedFractional`] — A `.` or `,` was present for a fractional part
582    ///   but no digits followed.
583    /// - [`DtErrKind::ExpectedUnit`] — A number was parsed but no unit designator
584    ///   (`Y`/`M`/`W`/`D`/`H`/`S` etc.) followed it.
585    /// - [`DtErrKind::InvalidNumber`] — A numeric component could not be parsed as an `i64`
586    ///   (typically too large).
587    /// - [`DtErrKind::InvalidBytes`] — Internal UTF-8 conversion failure while reading a number
588    ///   (should not occur for valid ASCII input).
589    /// - [`DtErrKind::InvalidFractional`] — The fractional part digits could not be parsed as an integer.
590    /// - [`DtErrKind::FracOutOfRange`] — More than 9 digits were supplied for fractional seconds.
591    /// - [`DtErrKind::InvalidItem`] — A fractional part was supplied on a unit other than seconds.
592    ///
593    /// ### Unit and range errors
594    ///
595    /// - [`DtErrKind::UnknownItem`] — An unknown unit designator character was used.
596    /// - [`DtErrKind::YearOutOfRange`], [`DtErrKind::MonthOutOfRange`],
597    ///   [`DtErrKind::WeekOutOfRange`], [`DtErrKind::DayOutOfRange`] — The component value
598    ///   (after sign) overflows when multiplied by the corresponding fixed-length constant
599    ///   (checked arithmetic).
600    /// - [`DtErrKind::OutOfRange`] — The accumulated duration does not fit in attoseconds
601    ///   when converting from nanoseconds (`checked_mul`).
602    pub fn from_iso_duration(s: &str) -> Result<Dt, DtErr> {
603        let len = s.len();
604        if len == 0 {
605            return Err(an_err!(DtErrKind::Empty));
606        }
607
608        let b = s.as_bytes();
609        let mut i = 0usize;
610
611        // Optional leading sign (+ or -)
612        let mut sign: i64 = 1;
613        if i < len && matches!(b[i], b'+' | b'-') {
614            if b[i] == b'-' {
615                sign = -1;
616            }
617            i += 1;
618        }
619
620        // Must start with P/p
621        if i >= len || !matches!(b[i], b'P' | b'p') {
622            return Err(an_err!(DtErrKind::MustStartWith));
623        }
624        i += 1;
625
626        // Find the (single) T/t separator
627        let t_pos = b[i..]
628            .iter()
629            .position(|&c| matches!(c, b'T' | b't'))
630            .map(|p| i + p);
631
632        let (date_part, time_part) = match t_pos {
633            Some(pos) => {
634                if pos == len - 1 {
635                    return Err(an_err!(DtErrKind::InvalidSyntax));
636                }
637                if b[pos + 1..].iter().any(|&c| matches!(c, b'T' | b't')) {
638                    return Err(an_err!(DtErrKind::InvalidSyntax));
639                }
640                (&b[i..pos], &b[pos + 1..])
641            }
642            None => (&b[i..], &[] as &[u8]),
643        };
644
645        let mut has_fraction = false;
646        let mut total_nanos: i128 = 0;
647
648        Self::parse_duration_part(date_part, &mut total_nanos, true, sign, &mut has_fraction)?;
649        Self::parse_duration_part(time_part, &mut total_nanos, false, sign, &mut has_fraction)?;
650
651        let total_attos = total_nanos
652            .checked_mul(ATTOS_PER_NS_I128)
653            .ok_or_else(|| an_err!(DtErrKind::OutOfRange))?;
654        Ok(dt!(total_attos))
655    }
656
657    /// Parses a single component (number + optional fraction + unit) from the slice,
658    /// advancing the index `i`. Returns [`Option::None`] when the slice is exhausted.
659    fn parse_next_component(
660        chars: &[u8],
661        i: &mut usize,
662        sign: i64,
663        has_fraction: &mut bool,
664    ) -> Result<Option<ParsedComponent>, DtErr> {
665        if *i >= chars.len() {
666            return Ok(None);
667        }
668
669        if *has_fraction {
670            return Err(an_err!(DtErrKind::TrailingCharacters));
671        }
672
673        // Parse integer part
674        let start = *i;
675        while *i < chars.len() && chars[*i].is_ascii_digit() {
676            *i += 1;
677        }
678        if start == *i {
679            return Err(an_err!(DtErrKind::ExpectedValue));
680        }
681
682        let int_str = core::str::from_utf8(&chars[start..*i])
683            .map_err(|e| an_err!(DtErrKind::InvalidBytes, "{}", e))?;
684        let int: i64 = int_str.parse().map_err(|e: core::num::ParseIntError| {
685            an_err!(DtErrKind::InvalidNumber, "{}: {}", int_str, e)
686        })?;
687
688        // Parse optional fraction
689        let mut frac_num: i64 = 0;
690        let mut frac_digits: usize = 0;
691        if *i < chars.len() && matches!(chars[*i], b'.' | b',') {
692            *i += 1;
693            let frac_start = *i;
694            while *i < chars.len() && chars[*i].is_ascii_digit() {
695                *i += 1;
696            }
697            frac_digits = *i - frac_start;
698            if frac_digits == 0 {
699                return Err(an_err!(DtErrKind::ExpectedFractional));
700            }
701            if frac_digits > 9 {
702                return Err(an_err!(DtErrKind::FracOutOfRange));
703            }
704
705            let frac_str = core::str::from_utf8(&chars[frac_start..*i])
706                .map_err(|e| an_err!(DtErrKind::InvalidBytes, "{}", e))?;
707            frac_num = frac_str.parse().map_err(|e: core::num::ParseIntError| {
708                an_err!(DtErrKind::InvalidFractional, "{}: {}", frac_str, e)
709            })?;
710        }
711
712        // Unit must follow
713        if *i >= chars.len() {
714            return Err(an_err!(DtErrKind::ExpectedUnit));
715        }
716        let unit = chars[*i];
717        *i += 1;
718
719        // Only seconds support a fractional part
720        if frac_digits > 0 {
721            if !matches!(unit, b'S' | b's') {
722                return Err(an_err!(DtErrKind::InvalidItem));
723            }
724            *has_fraction = true;
725        }
726
727        let signed_int = (int as i128 * sign as i128) as i64;
728
729        Ok(Some(ParsedComponent {
730            unit,
731            signed_int,
732            frac_digits,
733            frac_num,
734        }))
735    }
736
737    /// Helper that parses **one section** of an ISO duration (date or time part)
738    /// and accumulates nanoseconds into `total_nanos`.
739    ///
740    /// Years, months, weeks, and days are converted using the fixed-length
741    /// constants (the only sensible semantics for a pure `Dt`).
742    fn parse_duration_part(
743        chars: &[u8],
744        total_nanos: &mut i128,
745        is_date: bool,
746        sign: i64,
747        has_fraction: &mut bool,
748    ) -> Result<(), DtErr> {
749        let mut i = 0;
750        while let Some(comp) = Self::parse_next_component(chars, &mut i, sign, has_fraction)? {
751            let contrib_nanos = match (is_date, comp.unit) {
752                (true, b'Y' | b'y') => {
753                    let total_sec = (comp.signed_int as i128)
754                        .checked_mul(SEC_PER_YEAR)
755                        .ok_or_else(|| an_err!(DtErrKind::YearOutOfRange))?;
756                    total_sec * 1_000_000_000i128
757                }
758                (true, b'M' | b'm') => {
759                    let total_sec = (comp.signed_int as i128)
760                        .checked_mul(SEC_PER_MONTH)
761                        .ok_or_else(|| an_err!(DtErrKind::MonthOutOfRange))?;
762                    total_sec * 1_000_000_000i128
763                }
764                (true, b'W' | b'w') => {
765                    let total_sec = (comp.signed_int as i128)
766                        .checked_mul(SEC_PER_WEEK as i128)
767                        .ok_or_else(|| an_err!(DtErrKind::WeekOutOfRange))?;
768                    total_sec * 1_000_000_000i128
769                }
770                (true, b'D' | b'd') => {
771                    let total_sec = (comp.signed_int as i128)
772                        .checked_mul(SEC_PER_DAY)
773                        .ok_or_else(|| an_err!(DtErrKind::DayOutOfRange))?;
774                    total_sec * 1_000_000_000i128
775                }
776                (false, b'H' | b'h') => (comp.signed_int as i128) * 3_600_000_000_000i128,
777                (false, b'M' | b'm') => (comp.signed_int as i128) * 60_000_000_000i128,
778                (false, b'S' | b's') => {
779                    let mut sec_nanos = (comp.signed_int as i128) * 1_000_000_000i128;
780                    if comp.frac_digits > 0 {
781                        let frac_ns = (comp.frac_num as i128 * sign as i128 * 1_000_000_000i128)
782                            / 10i128.pow(comp.frac_digits as u32);
783                        sec_nanos += frac_ns;
784                    }
785                    sec_nanos
786                }
787                _ => {
788                    return Err(an_err!(DtErrKind::UnknownItem, "{}", comp.unit as char));
789                }
790            };
791
792            *total_nanos = total_nanos.saturating_add(contrib_nanos);
793        }
794        Ok(())
795    }
796
797    /// Parses a media-style duration string.
798    ///
799    /// Accepts formats like:
800    /// - `"0:45"`, `"9:41"`
801    /// - `"1:23:45"`
802    /// - `"1:07:54:30"`
803    /// - `"-1:23:45"`
804    ///
805    /// ## Errors
806    ///
807    /// Returns a [`DtErr`] if the input cannot be parsed as a valid media-style
808    /// duration. The error kind is available via [`DtErr::kind`].
809    ///
810    /// This function uses saturating arithmetic, so it never returns range or
811    /// overflow errors.
812    ///
813    /// ### Input / structure errors
814    ///
815    /// - [`DtErrKind::Empty`] — The string is empty or contains only ASCII whitespace.
816    /// - [`DtErrKind::InvalidInput`] — A single minus sign with nothing after it.
817    /// - [`DtErrKind::InvalidSyntax`] — The input does not contain exactly 2, 3, or 4
818    ///   colon-separated numeric components.
819    /// - [`DtErrKind::TrailingCharacters`] — Non-whitespace characters remain after
820    ///   the final numeric component.
821    ///
822    /// ### Parsing errors
823    ///
824    /// - [`DtErrKind::ExpectedValue`] — A component was expected to begin with a digit
825    ///   (either at the start of the string or immediately after a `:`) but did not.
826    ///
827    /// ## See also
828    ///
829    /// - [`Dt::to_str_media_duration`](../struct.Dt.html#method.to_str_media_duration)
830    /// - [`Dt::to_str_b_media_duration`](../struct.Dt.html#method.to_str_b_media_duration)
831    pub fn from_str_media_duration(input: &str) -> Result<Dt, DtErr> {
832        let bytes = input.as_bytes();
833        let len = bytes.len();
834        let mut pos: usize = 0;
835
836        // Skip leading whitespace
837        while pos < len && bytes[pos].is_ascii_whitespace() {
838            pos += 1;
839        }
840
841        if pos == len {
842            return Err(an_err!(DtErrKind::Empty));
843        }
844
845        // Optional single leading minus
846        let negative = if bytes[pos] == b'-' {
847            pos += 1;
848            if pos == len {
849                return Err(an_err!(DtErrKind::InvalidInput));
850            }
851            true
852        } else {
853            false
854        };
855
856        // Parse up to 4 numeric components separated by ':'
857        let mut components: [i128; 4] = [0; 4];
858        let mut count: usize = 0;
859
860        loop {
861            if count >= 4 {
862                break;
863            }
864
865            // Parse one number
866            if pos >= len || !bytes[pos].is_ascii_digit() {
867                return Err(an_err!(DtErrKind::ExpectedValue));
868            }
869
870            let mut value: i128 = 0;
871            while pos < len && bytes[pos].is_ascii_digit() {
872                value = value
873                    .saturating_mul(10)
874                    .saturating_add((bytes[pos] - b'0') as i128);
875                pos += 1;
876            }
877
878            components[count] = value;
879            count += 1;
880
881            // Check for more components
882            if pos >= len || bytes[pos] != b':' {
883                break;
884            }
885
886            pos += 1; // consume ':'
887
888            // Reject trailing ':' with no number after it
889            if pos >= len || !bytes[pos].is_ascii_digit() {
890                return Err(an_err!(DtErrKind::ExpectedValue));
891            }
892        }
893
894        if !(2..=4).contains(&count) {
895            return Err(an_err!(DtErrKind::InvalidSyntax));
896        }
897
898        // Skip trailing whitespace
899        while pos < len && bytes[pos].is_ascii_whitespace() {
900            pos += 1;
901        }
902
903        if pos != len {
904            return Err(an_err!(DtErrKind::TrailingCharacters));
905        }
906
907        // Convert to total seconds
908        let total_sec: i128 = match count {
909            2 => components[0] * 60 + components[1], // M:SS
910            3 => components[0] * 3600 + components[1] * 60 + components[2], // H:MM:SS
911            4 => components[0] * 86400 + components[1] * 3600 + components[2] * 60 + components[3], // D:H:MM:SS
912            _ => unreachable!(),
913        };
914
915        let total_sec = if negative { -total_sec } else { total_sec };
916
917        Ok(dt!(sec!(total_sec)))
918    }
919
920    /// Hours:Minutes elapsed time: `H:MM` or `H:MM:SS[.frac]` (hours unbounded).
921    ///
922    /// Minutes and seconds must be `0..=59`. Fractional seconds (optional) may
923    /// follow only the seconds field, up to 18 digits. Requires at least one
924    /// `:`. Optional leading `-` and ASCII whitespace. Returns a pure duration
925    /// on `Scale::TAI`.
926    ///
927    /// Not media duration: two fields are **hours:minutes**, not minutes:seconds.
928    #[inline]
929    pub fn from_str_h_mm_duration(input: &str) -> Result<Dt, DtErr> {
930        Ok(dt!(Self::h_mm_duration_attos(input)?))
931    }
932
933    /// Shared by [`from_str_h_mm_duration`] and relative natural parse.
934    pub(crate) fn h_mm_duration_attos(input: &str) -> Result<i128, DtErr> {
935        let bytes = input.as_bytes();
936        let len = bytes.len();
937        let mut pos = 0usize;
938
939        while pos < len && bytes[pos].is_ascii_whitespace() {
940            pos += 1;
941        }
942        if pos == len {
943            return Err(an_err!(DtErrKind::Empty));
944        }
945
946        let neg = if bytes[pos] == b'-' {
947            pos += 1;
948            if pos == len {
949                return Err(an_err!(DtErrKind::InvalidInput));
950            }
951            true
952        } else {
953            false
954        };
955
956        let hours = parse_uint(bytes, &mut pos, len)?;
957        // At least one colon is required (H:MM or H:MM:SS).
958        if pos >= len || bytes[pos] != b':' {
959            return Err(an_err!(DtErrKind::InvalidSyntax));
960        }
961        pos += 1;
962
963        let minutes = parse_uint(bytes, &mut pos, len)?;
964        if minutes > 59 {
965            return Err(an_err!(DtErrKind::InvalidInput));
966        }
967
968        let mut seconds: i128 = 0;
969        let mut frac_attos: i128 = 0;
970
971        if pos < len && bytes[pos] == b':' {
972            pos += 1;
973            seconds = parse_uint(bytes, &mut pos, len)?;
974            if seconds > 59 {
975                return Err(an_err!(DtErrKind::InvalidInput));
976            }
977            if pos < len && bytes[pos] == b'.' {
978                pos += 1;
979                if pos >= len || !bytes[pos].is_ascii_digit() {
980                    return Err(an_err!(DtErrKind::ExpectedValue));
981                }
982                let mut digits = 0u32;
983                let mut frac = 0i128;
984                while pos < len && bytes[pos].is_ascii_digit() {
985                    if digits < 18 {
986                        frac = frac
987                            .saturating_mul(10)
988                            .saturating_add((bytes[pos] - b'0') as i128);
989                        digits += 1;
990                    }
991                    pos += 1;
992                }
993                frac_attos = frac.saturating_mul(10i128.pow(18 - digits));
994            }
995        } else if pos < len && bytes[pos] == b'.' {
996            // No fractional minutes.
997            return Err(an_err!(DtErrKind::InvalidSyntax));
998        }
999
1000        while pos < len && bytes[pos].is_ascii_whitespace() {
1001            pos += 1;
1002        }
1003        if pos != len {
1004            return Err(an_err!(DtErrKind::TrailingCharacters));
1005        }
1006
1007        let mut attos = hours
1008            .saturating_mul(3600)
1009            .saturating_add(minutes.saturating_mul(60))
1010            .saturating_add(seconds)
1011            .saturating_mul(ATTOS_PER_SEC_I128)
1012            .saturating_add(frac_attos);
1013        if neg {
1014            attos = -attos;
1015        }
1016        Ok(attos)
1017    }
1018}
1019
1020fn parse_uint(bytes: &[u8], pos: &mut usize, len: usize) -> Result<i128, DtErr> {
1021    if *pos >= len || !bytes[*pos].is_ascii_digit() {
1022        return Err(an_err!(DtErrKind::ExpectedValue));
1023    }
1024    let mut v: i128 = 0;
1025    while *pos < len && bytes[*pos].is_ascii_digit() {
1026        v = v
1027            .saturating_mul(10)
1028            .saturating_add((bytes[*pos] - b'0') as i128);
1029        *pos += 1;
1030    }
1031    Ok(v)
1032}