deep-time 0.1.0-beta.29

High-precision, no-std, no-alloc date-time library, leap-seconds, time scales, relativistic time, and a powerful date & duration parser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
use crate::en::parse_month_name_abbrev;
use crate::{DtErr, DtErrKind, Offset, Parts, STRTIME_SIZE, Scale, Weekday, an_err};

impl Parts {
    /// Fast, no-alloc parser for common ISO-like and epoch-style date-time strings.
    ///
    /// Returns raw civil / numeric components in a [`Parts`] value (not a resolved
    /// instant). Convert with [`Parts::to_dt`](struct.Parts.html#method.to_dt) when you
    /// need a [`Dt`](../struct.Dt.html).
    ///
    /// - Only **ASCII** input is supported.
    /// - Inputs longer than [`STRTIME_SIZE`](../consts/constant.STRTIME_SIZE.html) are
    ///   rejected with [`DtErrKind::InvalidLen`](../error/enum.DtErrKind.html#variant.InvalidLen).
    /// - Leading non-date junk is skipped until a year-like start (`digit` or `±`digit)
    ///   or a recognized alphabetic prefix (`JD` / `MJD` / `SEC`, case-insensitive).
    /// - Trailing characters after a successful parse are generally ignored (lenient).
    /// - Considerably faster than format-string / smart parsers when the input is one
    ///   of the shapes below.
    ///
    /// ## Default scale on the returned [`Parts`]
    ///
    /// - **Calendar / day-of-year / ISO week** with no trailing scale → [`Scale::UTC`].
    /// - **`SEC` / `JD` / `MJD`** with no trailing scale → [`Scale::TAI`].
    /// - A trailing library scale (e.g. `TAI`, `TDB`, `GPS`) is accepted on **all**
    ///   formats and overrides the default.
    ///
    /// ## Supported formats
    ///
    /// ### ISO-like civil date-times
    ///
    /// #### Format examples
    ///
    /// - **`+2000-01-01T17:00:00 -0500 [America/New_York] TAI`**
    /// - **`2024 Apr 18, 14:30:25 [America/New_York]`** — month abbrev or full English name
    /// - **`2024-109 14:30:25`** — day of year (`%Y-%j`)
    /// - **`2024-W11`**, **`2024W11`**, **`2024-W11-4`** — ISO week date (`%G-W%V`, optional
    ///   weekday `%u` with Monday=`1` … Sunday=`7`)
    /// - **`2024`**, **`2024-03`**, **`2024 Mar`** — partial dates (see below)
    /// - **`2024-04-18T9:3:5.5`**, **`2024-04-18T143025`** — flexible / compact time
    ///
    /// #### Date forms (after an optional sign and year digits)
    ///
    /// Year digits are taken **literally** (no century window): `99-01-01` is year 99 AD.
    /// Year overflow during accumulation yields
    /// [`DtErrKind::YearOutOfRange`](../error/enum.DtErrKind.html#variant.YearOutOfRange).
    ///
    /// Exactly one of the following is used:
    ///
    /// 1. **ISO week** — `W`/`w` immediately after the year (or after a non-letter
    ///    separator such as `-`): e.g. `2024-W11`, `2024W114`.
    ///    - Sets [`Parts::iso_wk_yr`] / [`Parts::iso_wk`] (and optional [`Parts::wkday`]);
    ///      clears calendar [`Parts::yr`].
    ///    - Week number required right after `W` (1–2 digits); `0` becomes week `1`.
    ///    - Optional weekday: `-4` or basic trailing digit `1..=7`.
    ///    - This is **not** strftime `%W` (Monday week-of-year on a calendar year).
    /// 2. **Day of year** — three slots `[digit|space][digit|space][digit]` not followed
    ///    by another digit (so `2024-0401` is calendar `04-01`, not DOY). Space padding
    ///    is allowed (`2024-  9`). Sets [`Parts::day_of_yr`].
    /// 3. **Calendar month/day** — numeric month (1–2 digits) or English month name
    ///    (abbrev or full; matched from the first three letters), then day (1–2 digits).
    ///
    /// **Partial calendar dates** default missing fields to `1` (January / day 1):
    ///
    /// - Year only: `2024`, `2024-` → 1 January.
    /// - Year-month: `2024-03`, `2024 Mar` → day 1.
    /// - Explicit zero month/day digits are treated like omitted (`2024-00`, `2024-03-0` → 1).
    /// - Year or year-month may be followed by time: `2024T12:00`, `2024-03T12:00`
    ///   (the `T` is not read as a day field).
    ///
    /// #### Time (optional)
    ///
    /// - Usually introduced by `T`/`t`, space, or another non-digit separator; compact
    ///   glued times after a full day are also accepted (e.g. `…18143025`).
    /// - Hour, minute, and second are **1 or 2** digits when the field ends at `:` /
    ///   space (or, for seconds, `.` before a fraction).
    /// - Compact digit runs without separators are supported (e.g. `T143025`).
    /// - Fractional seconds: `.` then digits (up to 18 kept as attoseconds; extra digits
    ///   ignored).
    /// - Optional trailing `Z`/`z` is consumed (does not set a numeric offset by itself).
    /// - Minutes must be `≤ 59`; seconds must be `≤ 60` (leap second `60` allowed).
    ///
    /// #### Optional trailing components
    ///
    /// - **Offset** — `+`/`-` then hours (and optional minutes), with or without `:`:
    ///   `+02:00`, `-0530`, also allowed directly after the date.
    /// - **IANA name** — must be in square brackets, e.g. `[America/New_York]`.
    ///   Resolving non-UTC aliases requires the `jiff-tz` or `jiff-tz-bundle` feature
    ///   (both require `alloc`).
    /// - **Scale** — library abbreviation, e.g. `TAI`, `UTC`, `TDB`, `GPS`.
    ///
    /// ### Seconds since 2000-01-01 noon (library epoch)
    ///
    /// #### Format examples
    ///
    /// - **`SEC 1234.567 TDB`**
    /// - **`sec1234.5 TAI`**
    ///
    /// #### Notes
    ///
    /// - `sec` prefix is required (case-insensitive).
    /// - Fractional seconds optional; sets [`Parts::timestamp`] with
    ///   [`Epoch::Noon2000`](enum.Epoch.html#variant.Noon2000).
    ///
    /// ### Julian Date
    ///
    /// #### Format examples
    ///
    /// - **`JD 2451545.0 TAI`**
    /// - **`JD2451545.25 TT`**
    ///
    /// #### Notes
    ///
    /// - `jd` prefix is required (case-insensitive).
    /// - Fractional days optional; result is a [`Parts::timestamp`] on
    ///   [`Epoch::Noon2000`](enum.Epoch.html#variant.Noon2000).
    ///
    /// ### Modified Julian Date
    ///
    /// #### Format examples
    ///
    /// - **`MJD 51544.5 TT`**
    /// - **`mjd 51544.25`**
    ///
    /// #### Notes
    ///
    /// - `mjd` prefix is required (case-insensitive).
    /// - Fractional days optional; same timestamp representation as JD.
    ///
    /// ## See also
    ///
    /// - [`Dt::from_str`](../struct.Dt.html#method.from_str) — same input, returns
    ///   a [`Dt`](../struct.Dt.html) on TAI via [`Parts::to_dt`](struct.Parts.html#method.to_dt).
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Result<Self, DtErr> {
        let bytes = s.as_bytes();
        let len_ = bytes.len();
        if len_ > STRTIME_SIZE {
            return Err(an_err!(DtErrKind::InvalidLen));
        }

        let mut start = 0usize;
        while start < len_ {
            let b = bytes[start];
            if b.is_ascii_digit()
                || (matches!(b, b'+' | b'-')
                    && start + 1 < len_
                    && bytes[start + 1].is_ascii_digit())
            {
                break;
            }

            if b.is_ascii_alphabetic() {
                match detect_word(bytes, b, start, len_) {
                    Word::Jd => {
                        if let Some(p) = Self::from_str_jd_f(&s[start..], None) {
                            return Ok(p);
                        }
                    }
                    Word::Mjd => {
                        if let Some(p) = Self::from_str_mjd_f(&s[start..], None) {
                            return Ok(p);
                        }
                    }
                    Word::Sec => {
                        if let Some(p) = Self::from_str_sec_f(&s[start..], None) {
                            return Ok(p);
                        }
                    }
                    _ => {}
                }
                start = next_item(bytes, start, len_);
            } else {
                start += 1;
            }
        }

        if start == len_ {
            return Err(an_err!(DtErrKind::ExpectedYear));
        }

        let s = &s[start..];
        let bytes = s.as_bytes();
        let len_ = bytes.len();
        let mut pos: usize = 0;
        let mut tp = Parts::new_utc();

        // Year (manual accumulation, optional sign)
        let mut year: i64 = 0;
        let negative_year = if pos < len_ && matches!(bytes[pos], b'+' | b'-') {
            let neg = bytes[pos] == b'-';
            pos += 1;
            neg
        } else {
            false
        };

        if bytes[pos].is_ascii_digit() {
            while pos < len_ && bytes[pos].is_ascii_digit() {
                let digit = (bytes[pos] - b'0') as i64;
                year = year
                    .checked_mul(10)
                    .and_then(|n| n.checked_add(digit))
                    .ok_or_else(|| an_err!(DtErrKind::YearOutOfRange))?;
                pos += 1;
            }
        } else {
            return Err(an_err!(DtErrKind::ExpectedYear));
        }

        if negative_year {
            year = -year;
        }
        tp.yr = Some(year);

        // required separator after year
        if pos < len_ {
            if !bytes[pos].is_ascii_alphabetic() {
                pos += 1;
            }
        } else {
            // Year only → 1 Jan
            tp.mo = Some(1);
            tp.day = Some(1);
            return Ok(tp);
        }

        // ISO week date (`2024-W11`, `2024W11`, optional weekday `…-4` / `…4`)
        // or day-of-year or calendar month/day.
        // `%G-W%V` / `%G-W%V-%u` — not strftime `%W` (that is calendar `wk_mon`).
        if pos < len_ && matches!(bytes[pos], b'W' | b'w') {
            // Require a digit immediately after W before mutating Parts.
            let mut p = pos + 1;
            if p >= len_ || !bytes[p].is_ascii_digit() {
                return Err(an_err!(DtErrKind::ExpectedWeekNumber));
            }
            let mut week = bytes[p] - b'0';
            p += 1;
            if p < len_ && bytes[p].is_ascii_digit() {
                week = week * 10 + (bytes[p] - b'0');
                p += 1;
            }

            // Optional weekday Mon=1…Sun=7: extended `…-4` or basic trailing digit.
            let mut wkday = None;
            if p < len_ {
                let b = bytes[p];
                if b == b'-' {
                    let dpos = p + 1;
                    if dpos < len_ && bytes[dpos].is_ascii_digit() {
                        let d = bytes[dpos] - b'0';
                        wkday = Some(
                            Weekday::from_monday_1_based(d)
                                .ok_or(an_err!(DtErrKind::ExpectedWeekdayNumber))?,
                        );
                        p = dpos + 1;
                    }
                    // Lone `-` left for later stages.
                } else if b.is_ascii_digit() {
                    // Basic `YYYYWwwD` — only consume if valid ISO weekday.
                    if let Some(wd) = Weekday::from_monday_1_based(b - b'0') {
                        wkday = Some(wd);
                        p += 1;
                    }
                }
            }

            pos = p;
            tp.iso_wk_yr = tp.yr.take();
            tp.iso_wk = Some(if week == 0 { 1 } else { week });
            tp.wkday = wkday;
            // Missing weekday → Monday in to_dt via unwrap_or.
        } else if let Some(doy) = try_parse_doy(bytes, &mut pos, len_) {
            tp.day_of_yr = Some(doy);
        } else {
            'day_month: {
                while pos < len_
                    && (bytes[pos].is_ascii_whitespace() || bytes[pos].is_ascii_punctuation())
                {
                    pos += 1;
                }
                if pos >= len_ {
                    // Year only (trailing junk/separators) → 1 Jan
                    tp.mo = Some(1);
                    tp.day = Some(1);
                    return Ok(tp);
                }

                // Year-only + time (`2024T12:00`): keep `T` for the time stage.
                if matches!(bytes[pos], b'T' | b't') {
                    tp.mo = Some(1);
                    tp.day = Some(1);
                    break 'day_month;
                }

                // Abbreviated/full month or 1 or 2 digit month
                if bytes[pos].is_ascii_digit() {
                    let mut mo: u8;
                    mo = bytes[pos] - b'0';
                    pos += 1;
                    if pos < len_ && bytes[pos].is_ascii_digit() {
                        mo = mo * 10 + (bytes[pos] - b'0');
                        pos += 1;
                    }
                    // 0 → January (zero / missing month field → default).
                    tp.mo = Some(if mo == 0 { 1 } else { mo });
                } else if bytes[pos].is_ascii_alphabetic() && pos + 3 <= len_ {
                    // `<=` so bare "Mar" at EOS matches (exactly 3 letters).
                    tp.mo = Some(
                        parse_month_name_abbrev(&bytes[pos..])
                            .ok_or(an_err!(DtErrKind::InvalidMonthName))?,
                    );
                    // pos stays on the name; non-digit skip below walks past it.
                }

                // Skip to day; stop before `T`/`t` so `2024-03T12:00` is time, not day.
                while pos < len_ {
                    let b = bytes[pos];
                    if b.is_ascii_digit() {
                        break;
                    }
                    if matches!(b, b'T' | b't') && !bytes[pos - 1].is_ascii_alphabetic() {
                        // Year-month only (+ time) → day 1; mo already set (or default below).
                        tp.mo.get_or_insert(1);
                        tp.day = Some(1);
                        break 'day_month;
                    }
                    pos += 1;
                }
                if pos >= len_ {
                    // Year-month only → day 1
                    tp.mo.get_or_insert(1);
                    tp.day = Some(1);
                    return Ok(tp);
                }

                // 1 or 2 digit day
                let mut day = bytes[pos] - b'0';
                pos += 1;
                if pos < len_ && bytes[pos].is_ascii_digit() {
                    day = day * 10 + (bytes[pos] - b'0');
                    pos += 1;
                }
                // 0 → day 1 (zero / missing day field → default).
                tp.day = Some(if day == 0 { 1 } else { day });
            }
        }

        // required date-time separator
        while pos < len_ && bytes[pos].is_ascii_whitespace() {
            pos += 1;
        }
        if pos >= len_ {
            return Ok(tp);
        }
        // push past a T
        if !bytes[pos].is_ascii_digit() && pos + 1 < len_ && !matches!(bytes[pos], b'+' | b'-') {
            if bytes[pos + 1].is_ascii_digit() {
                pos += 1;
            } else if bytes[pos + 1].is_ascii_whitespace() || bytes[pos + 1].is_ascii_punctuation()
            {
                pos += 1;
                while pos < len_
                    && (bytes[pos].is_ascii_whitespace() || bytes[pos].is_ascii_punctuation())
                {
                    pos += 1;
                }
            }
        }
        if pos >= len_ {
            return Ok(tp);
        }

        // Optional time components
        'time: {
            if !bytes[pos].is_ascii_digit() {
                break 'time;
            }

            // Hour
            // digit 1
            tp.hr = bytes[pos] - b'0';
            pos += 1;
            // digit 2
            if pos >= len_ {
                return Ok(tp);
            }
            if bytes[pos].is_ascii_digit() {
                tp.hr = tp.hr * 10 + (bytes[pos] - b'0');
                pos += 1;
            } else if !matches!(bytes[pos], b':' | b' ') {
                break 'time;
            }

            if pos >= len_ {
                return Ok(tp);
            }
            // only continue if it's not a + or - and not an alpha
            if matches!(bytes[pos], b'A'..=b'Z' | b'a'..=b'z' | b'+' | b'-') {
                break 'time;
            }

            // perhaps a separator between H and M
            if !bytes[pos].is_ascii_digit() {
                pos += 1;
                if pos >= len_ {
                    return Ok(tp);
                }
            }

            // Minutes
            // digit 1
            if bytes[pos].is_ascii_digit() {
                tp.min = bytes[pos] - b'0';
                pos += 1;
            } else {
                break 'time;
            }
            // digit 2
            if pos >= len_ {
                return Ok(tp);
            }
            if bytes[pos].is_ascii_digit() {
                tp.min = tp.min * 10 + (bytes[pos] - b'0');
                pos += 1;
            } else if !matches!(bytes[pos], b':' | b' ') {
                break 'time;
            }
            if tp.min > 59 {
                return Err(an_err!(DtErrKind::MinuteOutOfRange));
            }

            if pos >= len_ {
                return Ok(tp);
            }
            // only continue if it's not a + or - and not an alpha
            if matches!(bytes[pos], b'A'..=b'Z' | b'a'..=b'z' | b'+' | b'-') {
                break 'time;
            }

            // perhaps a separator between M and S
            if !bytes[pos].is_ascii_digit() {
                pos += 1;
                if pos >= len_ {
                    return Ok(tp);
                }
            }

            // Seconds
            // digit 1
            if bytes[pos].is_ascii_digit() {
                tp.sec = bytes[pos] - b'0';
                pos += 1;
            } else {
                break 'time;
            }
            // digit 2
            if pos >= len_ {
                return Ok(tp);
            }
            if bytes[pos].is_ascii_digit() {
                tp.sec = tp.sec * 10 + (bytes[pos] - b'0');
                pos += 1;
            } else if !matches!(bytes[pos], b':' | b' ' | b'.') {
                // `:` / space: 1-digit sec field ends; `.` continues into fractional seconds.
                break 'time;
            }
            if tp.sec > 60 {
                return Err(an_err!(DtErrKind::SecondOutOfRange));
            }

            if pos >= len_ {
                return Ok(tp);
            }
            // only continue if it's not a + or - and not an alpha
            if matches!(bytes[pos], b'A'..=b'Z' | b'a'..=b'z' | b'+' | b'-') {
                break 'time;
            }

            // perhaps a . between S and fractional S
            if bytes[pos] == b'.' {
                pos += 1;
                if pos >= len_ {
                    return Ok(tp);
                }
            }

            // Fractional seconds (with or without leading dot)
            if !bytes[pos].is_ascii_digit() {
                break 'time;
            }
            tp.attos = (bytes[pos] - b'0') as u64;
            pos += 1;
            let mut digits_seen: usize = 1;
            while pos < len_ && bytes[pos].is_ascii_digit() {
                if digits_seen < 18 {
                    tp.attos = tp.attos * 10 + (bytes[pos] - b'0') as u64;
                    digits_seen += 1;
                }
                // Ignore any digits beyond the first 18
                pos += 1;
            }
            if digits_seen > 0 {
                tp.attos *= 10u64.pow(18u32.saturating_sub(digits_seen as u32));
            }
        }
        // Optional trailing Z/z
        if pos < len_ && matches!(bytes[pos], b'Z' | b'z') {
            pos += 1;
        }

        // Skip any whitespace
        while pos < len_ && bytes[pos].is_ascii_whitespace() {
            pos += 1;
        }
        if pos >= len_ {
            return Ok(tp);
        }

        // Optional offset
        if matches!(bytes[pos], b'+' | b'-') {
            let sign: i64 = if bytes[pos] == b'+' { 1 } else { -1 };
            pos += 1;

            // Parse hours (up to 2 digits). "+05:30"/"+0530"
            let mut hours: i64 = 0;
            let mut h_digits = 0usize;
            while pos < len_ && bytes[pos].is_ascii_digit() && h_digits < 2 {
                hours = hours * 10 + (bytes[pos] - b'0') as i64;
                pos += 1;
                h_digits += 1;
            }

            if h_digits > 0 {
                // Optional ':' separator before minutes
                if pos < len_ && bytes[pos] == b':' {
                    pos += 1;
                }

                // Parse minutes (up to 2 digits; optional)
                let mut minutes: i64 = 0;
                let mut m_digits = 0usize;
                while pos < len_ && bytes[pos].is_ascii_digit() && m_digits < 2 {
                    minutes = minutes * 10 + (bytes[pos] - b'0') as i64;
                    pos += 1;
                    m_digits += 1;
                }

                let total_sec_i64 = sign * (hours * 3600 + minutes * 60);
                let total_seconds: i32 =
                    total_sec_i64.clamp(i32::MIN as i64, i32::MAX as i64) as i32;
                tp.offset = Some(Offset::Fixed(total_seconds));
            }
        }

        // Skip any whitespace before IANA name or scale
        while pos < len_ && bytes[pos].is_ascii_whitespace() {
            pos += 1;
        }
        if pos >= len_ {
            return Ok(tp);
        }

        // Optional IANA timezone name in square brackets, e.g. [America/New_York]
        // Must be explicitly wrapped in [] so we don't mistake a scale for a zone.
        if bytes[pos] == b'[' {
            pos += 1; // skip '['

            let name_start = pos;

            while pos < len_ && bytes[pos] != b']' {
                pos += 1;
            }

            if pos >= len_ {
                return Err(an_err!(DtErrKind::InvalidTimeZone));
            }

            // pos is now at ']'
            let iana_bytes = &bytes[name_start..pos];

            let iana =
                core::str::from_utf8(iana_bytes).map_err(|_| an_err!(DtErrKind::InvalidBytes))?;

            tp.set_iana_name(Some(iana));
            pos += 1; // consume ']'
            if pos >= len_ {
                return Ok(tp);
            }
        }

        // Optional trailing scale (e.g. TAI, UTC)
        if let Some(sc) = Self::parse_scale(&bytes[pos..]) {
            tp.scale = sc;
        }

        Ok(tp)
    }

    /// Parse a time scale abbreviation from a bytes slice.
    /// Skips leading non-alphabetic bytes, then takes up to 8 ASCII alphabetic
    /// characters and attempts to interpret them as a scale via [`Scale::from_abbrev`].
    #[inline(always)]
    pub(crate) fn parse_scale(bytes: &[u8]) -> Option<Scale> {
        let len_ = bytes.len();
        let mut pos = 0usize;
        while pos < len_ && !bytes[pos].is_ascii_alphabetic() {
            pos += 1;
        }
        if pos < len_
            && let Ok(s) = core::str::from_utf8(&bytes[pos..(pos + 8).min(len_)])
        {
            return Scale::from_abbrev(s);
        }
        None
    }
}

/// Parse a day-of-year field in one pass: three slots
/// `[digit|space][digit|space][digit]`, not followed by another digit
/// (so `0401` stays calendar `04-01`, not DOY).
///
/// Spaces pad and do not force a ×10 (same as before: `"  9"` → 9, `"1 1"` → 11).
/// On success advances `*pos` past the field; on failure leaves `*pos` unchanged.
#[inline(always)]
fn try_parse_doy(bytes: &[u8], pos: &mut usize, len_: usize) -> Option<u16> {
    let start = *pos;
    let mut p = start;
    let mut doy: u16 = 0;

    // slot 1: digit or space
    if p >= len_ {
        return None;
    }
    let b = bytes[p];
    if b.is_ascii_digit() {
        doy = (b - b'0') as u16;
    } else if b != b' ' {
        return None;
    }
    p += 1;

    // slot 2: digit or space
    if p >= len_ {
        return None;
    }
    let b = bytes[p];
    if b.is_ascii_digit() {
        doy = doy * 10 + (b - b'0') as u16;
    } else if b != b' ' {
        return None;
    }
    p += 1;

    // slot 3: must be digit
    if p >= len_ || !bytes[p].is_ascii_digit() {
        return None;
    }
    doy = doy * 10 + (bytes[p] - b'0') as u16;
    p += 1;

    // not a 4+ digit run (calendar mo+day glued, etc.)
    if p < len_ && bytes[p].is_ascii_digit() {
        return None;
    }

    *pos = p;
    Some(doy)
}

enum Word {
    None,
    Sec,
    Jd,
    Mjd,
}

/// Detect `JD` (2 letters), `MJD` / `SEC` (3 letters) at `pos`.
/// `JD` only needs two bytes so forms like `JD1` / `jd2451545` match.
#[inline(always)]
fn detect_word(bytes: &[u8], b: u8, pos: usize, len_: usize) -> Word {
    match b {
        b'J' | b'j' => {
            // "JD…" — two bytes is enough
            if pos + 2 <= len_ && bytes[pos + 1].eq_ignore_ascii_case(&b'D') {
                Word::Jd
            } else {
                Word::None
            }
        }
        b'M' | b'm' => {
            if pos + 3 <= len_
                && bytes[pos + 1].eq_ignore_ascii_case(&b'J')
                && bytes[pos + 2].eq_ignore_ascii_case(&b'D')
            {
                Word::Mjd
            } else {
                Word::None
            }
        }
        b'S' | b's' => {
            if pos + 3 <= len_
                && bytes[pos + 1].eq_ignore_ascii_case(&b'E')
                && bytes[pos + 2].eq_ignore_ascii_case(&b'C')
            {
                Word::Sec
            } else {
                Word::None
            }
        }
        _ => Word::None,
    }
}

#[inline(always)]
fn next_item(bytes: &[u8], mut pos: usize, len_: usize) -> usize {
    while pos < len_ && bytes[pos].is_ascii_alphabetic() {
        pos += 1;
    }
    while pos < len_ && bytes[pos].is_ascii_whitespace() {
        pos += 1;
    }

    pos
}