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