grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
// Project:   grippo
// File:      src/time/mod.rs
// Purpose:   Timestamps to instants and back: grok forms, epoch, TAI64N, RFC 2822, strptime, Java
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Turn a matched timestamp into an instant, and write an instant out.
//!
//! `HTTPDATE` and `SYSLOGTIMESTAMP` are checked by their grok field scanner
//! first, so they accept exactly what the grok pattern matched. ISO 8601
//! reads what `TIMESTAMP_ISO8601` matches, comma fractions and `+1100`
//! offsets included, and RFC 3339's lowercase forms. A text with no offset
//! takes the caller's default.

#![allow(
    clippy::many_single_char_names,
    reason = "byte splitting reads h[i] at positions the way the field scanners do"
)]

use jiff::Timestamp;
use jiff::civil::DateTime;
use jiff::tz::{Offset, TimeZone};
use thiserror::Error;

use crate::field::{Scan, field};

mod cache;
mod chrono_format;
mod dialect;
mod java;
mod render;
pub use cache::FormatCache;
pub use chrono_format::ChronoFormat;
#[cfg(feature = "parse-grok")]
pub(crate) use chrono_format::{Item, Name, Number, Zone};
pub use dialect::StrptimeDialect;
pub use java::JavaPattern;
pub use render::{Fraction, RenderFormat, render, render_into};

/// How a timestamp is written.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TimeFormat {
    /// What grok's `TIMESTAMP_ISO8601` matches.
    Iso8601,
    /// [`TimeFormat::Iso8601`] with `T` between the date and time and `Z` for
    /// UTC, both upper case, as Elasticsearch's `ISO8601` date format reads
    /// it: `2026-11-30t10:00:00z` and `2026-11-30 10:00:00Z` are refused.
    Iso8601Strict,
    /// What grok's `HTTPDATE` matches: `26/Nov/2026:11:22:33 +1100`.
    HttpDate,
    /// What grok's `SYSLOGTIMESTAMP` matches. The year comes from the defaults.
    Syslog,
    /// A number since 1970-01-01 UTC, with an optional fraction, or a
    /// Windows count of 100 ns ticks, which takes none:
    /// [`EpochUnit::FileTime`] and [`EpochUnit::DotNetTicks`].
    Epoch(EpochUnit),
    /// The JSON date of .NET's `JavaScriptSerializer` and Windows PowerShell
    /// 5.1's `ConvertTo-Json`: `/Date(ms)/` or `/Date(ms+hhmm)/`, with or
    /// without a `\` before each `/`. The milliseconds since 1970-01-01 UTC
    /// may be negative and take no fraction. The offset, `+hhmm` or `-hhmm`,
    /// is the zone the writer was in, and moves no instant.
    MsJsonDate,
    /// RFC 2822, as mail and HTTP headers write it.
    Rfc2822,
    /// A strptime-style format in jiff's dialect, such as
    /// `%d/%b/%Y:%H:%M:%S %z`. [`TimeFormat::strptime`] translates another
    /// tool's.
    Strptime(String),
    /// A Java-style date pattern, such as `yyyy-MM-dd'T'HH:mm:ss.SSSXXX`,
    /// from [`TimeFormat::strptime`] with [`StrptimeDialect::Java`].
    Java(JavaPattern),
    /// A strptime format read exactly as chrono 0.4.45 reads it, from
    /// [`TimeFormat::strptime`] with [`StrptimeDialect::Chrono`].
    Chrono(ChronoFormat),
    /// A TAI64N label, `@` and 24 hex digits, as daemontools and runit write
    /// it. The label counts from 2^62 plus the 10 seconds TAI was ahead of UTC
    /// in 1970, and later leap seconds aren't in it.
    Tai64n,
}

/// The unit of an epoch number.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EpochUnit {
    /// Seconds.
    Seconds,
    /// Milliseconds.
    Millis,
    /// Microseconds.
    Micros,
    /// Nanoseconds.
    Nanos,
    /// The unit the number's size implies, sign aside: seconds up to 10^12,
    /// milliseconds up to 10^15, microseconds up to 10^18, nanoseconds above.
    /// Seconds cover 1970 to year 9999. The finer units start at 2001-09-09,
    /// and a finer count from before then reads one unit too coarse.
    ///
    /// A positive count of 18 digits is [`TimeError::UnitNeeded`]. Read as
    /// microseconds it lands in year 5138 or later, and it is the size of a
    /// Windows FILETIME or .NET tick count, which `Auto` never picks: name
    /// [`EpochUnit::FileTime`], [`EpochUnit::DotNetTicks`] or the unit.
    Auto,
    /// A Windows FILETIME: whole 100 ns ticks since 1601-01-01 UTC, as Active
    /// Directory's `lastLogonTimestamp`, `pwdLastSet` and `accountExpires` and
    /// `DateTime.ToFileTime()` write it. A sign or a fraction is
    /// [`TimeError::Shape`], and 0 and `i64::MAX`, which Windows writes for
    /// "never", are [`TimeError::Never`].
    FileTime,
    /// A .NET `DateTime.Ticks`: whole 100 ns ticks since 0001-01-01 on the
    /// clock the value was written from. A `Utc` value is UTC and a `Local`
    /// one is local time, which the count doesn't say, so [`TimeDefaults::zone`]
    /// places it and [`Stamp::offset`] is `None`. A sign or a fraction is
    /// [`TimeError::Shape`], and 0 (`DateTime.MinValue`) and `i64::MAX` are
    /// [`TimeError::Never`].
    DotNetTicks,
}

/// What a timestamp leaves out.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeDefaults {
    /// The zone for a timestamp that names no offset. UTC by default.
    /// `TimeZone::fixed` gives a fixed offset. A named zone, such as
    /// `TimeZone::get("Australia/Sydney")`, follows its daylight saving rules
    /// and needs the `time-tz` feature to look the name up.
    pub zone: TimeZone,
    /// The year for a timestamp that names none, such as BSD syslog's or a
    /// strptime format with a month and no year.
    pub year: Option<i16>,
    /// When the record was read, for a timestamp with no year when `year`
    /// is `None`: `year_rule` picks the year from this.
    pub now: Option<Timestamp>,
    /// How `now` gives the year of a timestamp with none.
    pub year_rule: YearRule,
}

impl Default for TimeDefaults {
    fn default() -> Self {
        Self {
            zone: TimeZone::UTC,
            year: None,
            now: None,
            year_rule: YearRule::Nearest,
        }
    }
}

/// How a timestamp with no year takes one from [`TimeDefaults::now`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum YearRule {
    /// The year that puts the month and day nearest `now`, so a December
    /// line read in early January lands in the year before.
    #[default]
    Nearest,
    /// The year `now` is in, in [`TimeDefaults::zone`], as Java resolves a
    /// pattern with no year.
    ThisYear,
}

/// An instant read from a timestamp, and the offset its text named.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Stamp {
    /// The instant.
    pub timestamp: Timestamp,
    /// The offset the text gave: a numeric offset or `Z`, a zone name's
    /// offset at that instant, or UTC for an epoch count or a TAI64N label.
    /// `None` when the text named none and [`TimeDefaults::zone`] placed it.
    pub offset: Option<Offset>,
}

impl Stamp {
    const fn zoned(timestamp: Timestamp, offset: Offset) -> Self {
        Self {
            timestamp,
            offset: Some(offset),
        }
    }

    const fn zone_less(timestamp: Timestamp) -> Self {
        Self {
            timestamp,
            offset: None,
        }
    }

    /// The zone to write the stamp in its text's own offset: that offset as
    /// a fixed zone, or `zone` for a text that named none. [`render`] in it
    /// writes `2026-11-30T10:00:00+10:00` back as it came.
    #[must_use]
    pub fn zone_or(&self, zone: &TimeZone) -> TimeZone {
        self.offset.map_or_else(|| zone.clone(), TimeZone::fixed)
    }
}

/// Why a timestamp didn't convert.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum TimeError {
    /// The text isn't in the format.
    #[error("not a {0} timestamp")]
    Shape(&'static str),
    /// A timestamp with no year, such as BSD syslog's, and none in the defaults.
    #[error("a timestamp with no year needs one in the defaults")]
    NoYear,
    /// A strptime directive with no jiff equivalent, such as `%Z`.
    #[error("strptime directive {0} can't be parsed")]
    Directive(String),
    /// A Java-style date pattern that doesn't build: a letter grippo doesn't
    /// read, such as `I` or `Q`, an unclosed quote, or a `]` with no `[`.
    #[error("Java-style date pattern {pattern:?} has {part}")]
    Pattern {
        /// The pattern as written.
        pattern: String,
        /// What can't be read, such as `letter QQ`.
        part: String,
    },
    /// The parts don't make a real instant: day 31 of November, hour 24.
    #[error(transparent)]
    Range(#[from] jiff::Error),
    /// 0 or `i64::MAX` as a Windows tick count: what Windows writes for a
    /// time that never was or never will be, such as an account that doesn't
    /// expire.
    #[error("a Windows tick count of 0 or 9223372036854775807, which mean never")]
    Never,
    /// An 18-digit count under [`EpochUnit::Auto`], which would read in year
    /// 5138 or later.
    #[error("an 18-digit count reads past year 5138 as Auto sizes it: name its unit")]
    UnitNeeded,
}

/// Convert `input`, written in `format`, to an instant.
///
/// # Errors
///
/// [`TimeError::Shape`] when the text isn't in the format, [`TimeError::NoYear`]
/// for a timestamp with no year and none in the defaults, and [`TimeError::Range`] when
/// the parts don't make a real instant.
pub fn parse_time(
    format: &TimeFormat,
    input: &[u8],
    defaults: &TimeDefaults,
) -> Result<Timestamp, TimeError> {
    parse_stamp(format, input, defaults).map(|stamp| stamp.timestamp)
}

/// [`parse_time`], with the offset the text named, or `None` where the
/// defaults' zone placed it.
///
/// # Errors
///
/// As [`parse_time`].
pub fn parse_stamp(
    format: &TimeFormat,
    input: &[u8],
    defaults: &TimeDefaults,
) -> Result<Stamp, TimeError> {
    match format {
        TimeFormat::Iso8601 => iso8601(input, defaults, false),
        TimeFormat::Iso8601Strict => iso8601(input, defaults, true),
        TimeFormat::HttpDate => httpdate(input),
        TimeFormat::Syslog => syslog(input, defaults),
        TimeFormat::Epoch(EpochUnit::FileTime) => Ok(Stamp::zoned(filetime(input)?, Offset::UTC)),
        TimeFormat::Epoch(EpochUnit::DotNetTicks) => dotnet_ticks(input, defaults),
        TimeFormat::Epoch(unit) => Ok(Stamp::zoned(epoch(input, *unit)?, Offset::UTC)),
        TimeFormat::MsJsonDate => ms_json_date(input),
        TimeFormat::Tai64n => Ok(Stamp::zoned(tai64n(input)?, Offset::UTC)),
        TimeFormat::Java(pattern) => pattern.parse(input, defaults),
        TimeFormat::Chrono(format) => format.parse(input, defaults),
        TimeFormat::Rfc2822 => {
            let s = std::str::from_utf8(input).map_err(|_| TimeError::Shape("RFC 2822"))?;
            let zoned = jiff::fmt::rfc2822::parse(s)?;
            Ok(Stamp::zoned(zoned.timestamp(), zoned.offset()))
        }
        TimeFormat::Strptime(fmt) => {
            let mut tm = jiff::fmt::strtime::parse(fmt.as_bytes(), input)?;
            if tm.year().is_none() && tm.month().is_some() {
                let month = tm.month().unwrap_or(1);
                let day = tm.day().unwrap_or(1);
                tm.set_year(Some(year_for(defaults, month, day)?))?;
            }
            if let Some(ts) = tm.timestamp() {
                // jiff drops a fraction parsed beside `%s`, as in `%s.%6f`.
                let ns = i64::from(tm.subsec_nanosecond().unwrap_or(0));
                let ns = if ts.as_second() < 0 { -ns } else { ns };
                let ts = ts.checked_add(jiff::SignedDuration::from_nanos(ns))?;
                Ok(Stamp::zoned(ts, Offset::UTC))
            } else if let Some(offset) = tm.offset() {
                Ok(Stamp::zoned(tm.to_timestamp()?, offset))
            } else if tm.iana_time_zone().is_some() {
                let zoned = tm.to_zoned_datetime()?;
                Ok(Stamp::zoned(zoned.timestamp(), zoned.offset()))
            } else {
                let ts = defaults.zone.to_timestamp(tm.to_datetime()?)?;
                Ok(Stamp::zone_less(ts))
            }
        }
    }
}

/// Convert `input` with the first of `formats` that reads it, as a list of
/// accepted forms is tried in order.
///
/// # Errors
///
/// The last format's error when none reads it, and [`TimeError::Shape`] for
/// an empty list.
pub fn parse_time_any(
    formats: &[TimeFormat],
    input: &[u8],
    defaults: &TimeDefaults,
) -> Result<Timestamp, TimeError> {
    parse_stamp_any(formats, input, defaults).map(|stamp| stamp.timestamp)
}

/// [`parse_time_any`], with the offset the text named as [`parse_stamp`]
/// gives it.
///
/// # Errors
///
/// As [`parse_time_any`].
pub fn parse_stamp_any(
    formats: &[TimeFormat],
    input: &[u8],
    defaults: &TimeDefaults,
) -> Result<Stamp, TimeError> {
    let mut last = TimeError::Shape("listed");
    for format in formats {
        match parse_stamp(format, input, defaults) {
            Ok(stamp) => return Ok(stamp),
            Err(e) => last = e,
        }
    }
    Err(last)
}

/// `input` is the whole of what the grok field `name` matches.
fn whole(name: &'static str, label: &'static str, input: &[u8]) -> Result<(), TimeError> {
    match field(name).map(|f| (f.scan)(input, 0)) {
        Some(Scan::Match(end)) if end == input.len() => Ok(()),
        _ => Err(TimeError::Shape(label)),
    }
}

/// ASCII digits as a number. The caller has checked they are digits.
fn num(digits: &[u8]) -> i64 {
    digits.iter().fold(0_i64, |n, &d| {
        n.saturating_mul(10).saturating_add(i64::from(d - b'0'))
    })
}

fn run(h: &[u8], i: usize) -> usize {
    h.get(i..)
        .map_or(0, |r| r.iter().take_while(|b| b.is_ascii_digit()).count())
}

/// Up to nine fraction digits as nanoseconds.
fn nanos(digits: &[u8]) -> i32 {
    let kept = &digits[..digits.len().min(9)];
    let scaled = num(kept) * 10_i64.pow(9 - u32::try_from(kept.len()).unwrap_or(9));
    i32::try_from(scaled).unwrap_or(0)
}

fn narrow<T: TryFrom<i64>>(n: i64) -> Result<T, TimeError> {
    T::try_from(n).map_err(|_| TimeError::Shape("in-range"))
}

/// `H:MM[:SS[.f]]` from `i`, as matched: hour, minute, second, nanos, end.
fn hms(h: &[u8], i: usize, seps: &[u8]) -> (i64, i64, i64, i32, usize) {
    let hd = run(h, i).min(2);
    let hour = num(&h[i..i + hd]);
    let m = i + hd + 1;
    let minute = num(&h[m..m + 2]);
    let mut e = m + 2;
    let mut second = 0;
    let mut frac = 0;
    if h.get(e) == Some(&b':') && run(h, e + 1) >= 2 {
        second = num(&h[e + 1..e + 3]);
        e += 3;
        if h.get(e).is_some_and(|b| seps.contains(b)) && run(h, e + 1) > 0 {
            let n = run(h, e + 1);
            frac = nanos(&h[e + 1..e + 1 + n]);
            e += 1 + n;
        }
    }
    (hour, minute, second, frac, e)
}

fn civil(y: i64, mo: i64, d: i64, hms: (i64, i64, i64, i32)) -> Result<DateTime, TimeError> {
    let (h, mi, s, ns) = hms;
    Ok(DateTime::new(
        narrow(y)?,
        narrow(mo)?,
        narrow(d)?,
        narrow(h)?,
        narrow(mi)?,
        narrow(s)?,
        ns,
    )?)
}

/// `+HH` or `-HH`, then `MM` or `:MM` where `minutes` holds the byte they start at, as
/// an offset up to 23:59.
fn offset(h: &[u8], i: usize, minutes: Option<usize>) -> Result<Offset, TimeError> {
    let neg = h[i] == b'-';
    let hh = num(&h[i + 1..i + 3]);
    let mm = minutes.map_or(0, |at| num(&h[at..at + 2]));
    if hh > 23 || mm > 59 {
        return Err(TimeError::Shape("offset up to 23:59"));
    }
    let secs = narrow::<i32>((hh * 60 + mm) * 60)?;
    Ok(Offset::from_seconds(if neg { -secs } else { secs })?)
}

/// `n` ASCII digits at `i`.
fn digits_at(h: &[u8], i: usize, n: usize) -> bool {
    h.get(i..i + n)
        .is_some_and(|d| d.iter().all(u8::is_ascii_digit))
}

/// What grok's `TIMESTAMP_ISO8601` matches, and RFC 3339's lowercase `t` and
/// `z`, and an offset of hours alone.
/// `strict` takes only an upper-case `T` and `Z`.
fn iso8601(h: &[u8], d: &TimeDefaults, strict: bool) -> Result<Stamp, TimeError> {
    let shape = || TimeError::Shape("ISO 8601");
    let date = digits_at(h, 0, 4)
        && h.get(4) == Some(&b'-')
        && digits_at(h, 5, 2)
        && h.get(7) == Some(&b'-')
        && digits_at(h, 8, 2)
        && (h.get(10) == Some(&b'T') || !strict && matches!(h.get(10), Some(b't' | b' ')))
        && digits_at(h, 11, 2)
        && h.get(13) == Some(&b':')
        && digits_at(h, 14, 2);
    if !date {
        return Err(shape());
    }
    let (y, mo, day) = (num(&h[0..4]), num(&h[5..7]), num(&h[8..10]));
    let (hour, minute) = (num(&h[11..13]), num(&h[14..16]));
    let mut i = 16;
    let (mut second, mut frac) = (0, 0);
    let sec_at = if h.get(i) == Some(&b':') { i + 1 } else { i };
    let n = run(h, sec_at).min(2);
    if n > 0 {
        second = num(&h[sec_at..sec_at + n]);
        if second > 60 {
            return Err(shape());
        }
        i = sec_at + n;
        if h.get(i).is_some_and(|b| b":.,".contains(b)) && run(h, i + 1) > 0 {
            let f = run(h, i + 1);
            frac = nanos(&h[i + 1..i + 1 + f]);
            i += 1 + f;
        }
    } else if sec_at != i {
        return Err(shape());
    }
    let dt = civil(y, mo, day, (hour, minute, second, frac))?;
    let (off, end) = match h.get(i) {
        None => return Ok(Stamp::zone_less(d.zone.to_timestamp(dt)?)),
        Some(b'Z') => (Offset::UTC, i + 1),
        Some(b'z') if !strict => (Offset::UTC, i + 1),
        Some(b'+' | b'-') if digits_at(h, i + 1, 2) => {
            let colon = usize::from(h.get(i + 3) == Some(&b':'));
            let at = i + 3 + colon;
            if digits_at(h, at, 2) {
                (offset(h, i, Some(at))?, at + 2)
            } else {
                (offset(h, i, None)?, i + 3)
            }
        }
        Some(_) => return Err(shape()),
    };
    if end != h.len() {
        return Err(shape());
    }
    Ok(Stamp::zoned(off.to_timestamp(dt)?, off))
}

/// January = 1, from a name `MONTH` matched.
fn month_num(h: &[u8]) -> Option<i64> {
    const ABBR: [&[u8]; 12] = [
        b"Jan", b"Feb", b"Mar", b"Apr", b"May", b"Jun", b"Jul", b"Aug", b"Sep", b"Oct", b"Nov",
        b"Dec",
    ];
    let head = h.get(..3)?;
    ABBR.iter()
        .position(|a| *a == head)
        .and_then(|p| i64::try_from(p + 1).ok())
}

fn httpdate(h: &[u8]) -> Result<Stamp, TimeError> {
    whole("HTTPDATE", "HTTP date", h)?;
    let dd = run(h, 0);
    let day = num(&h[..dd]);
    let mo = month_num(&h[dd + 1..]).ok_or(TimeError::Shape("HTTP date"))?;
    let slash = dd + 1 + h[dd + 1..].iter().position(|&b| b == b'/').unwrap_or(0);
    let y = num(&h[slash + 1..slash + 5]);
    let (hour, minute, second, frac, e) = hms(h, slash + 6, b".,");
    let dt = civil(y, mo, day, (hour, minute, second, frac))?;
    let z = e + 1;
    let digits_at = if matches!(h.get(z), Some(b'+' | b'-')) {
        z + 1
    } else {
        z
    };
    if run(h, digits_at) != 4 {
        return Err(TimeError::Shape("HTTP date with a 4-digit offset"));
    }
    let mut with_sign = [b'+', 0, 0, 0, 0];
    with_sign[0] = if h.get(z) == Some(&b'-') { b'-' } else { b'+' };
    with_sign[1..].copy_from_slice(&h[digits_at..digits_at + 4]);
    let off = offset(&with_sign, 0, Some(3))?;
    Ok(Stamp::zoned(off.to_timestamp(dt)?, off))
}

fn syslog(h: &[u8], d: &TimeDefaults) -> Result<Stamp, TimeError> {
    whole("SYSLOGTIMESTAMP", "syslog", h)?;
    let mo = month_num(h).ok_or(TimeError::Shape("syslog"))?;
    let after_name = h.iter().position(|&b| b == b' ').unwrap_or(0);
    let p = after_name + h[after_name..].iter().take_while(|&&b| b == b' ').count();
    let dd = run(h, p);
    let day = num(&h[p..p + dd]);
    let year = year_for(d, narrow(mo)?, narrow(day)?)?;
    let (hour, minute, second, frac, _) = hms(h, p + dd + 1, b".,");
    let dt = civil(i64::from(year), mo, day, (hour, minute, second, frac))?;
    Ok(Stamp::zone_less(d.zone.to_timestamp(dt)?))
}

/// The year for a date with none: the configured one, else the one
/// `d.year_rule` takes from `now`.
fn year_for(d: &TimeDefaults, month: i8, day: i8) -> Result<i16, TimeError> {
    if let Some(year) = d.year {
        return Ok(year);
    }
    let now = d.zone.to_datetime(d.now.ok_or(TimeError::NoYear)?).date();
    match d.year_rule {
        YearRule::Nearest => Ok(nearest_year(now, month, day)),
        YearRule::ThisYear => Ok(now.year()),
    }
}

/// The year that puts month and day nearest `now`, a day's date compared
/// with a day's.
fn nearest_year(now: jiff::civil::Date, month: i8, day: i8) -> i16 {
    let distance = |year: i16| {
        jiff::civil::Date::new(year, month, day.min(28))
            .ok()
            .and_then(|date| now.until(date).ok())
            .map_or(i64::MAX, |span| i64::from(span.get_days()).abs())
    };
    let here = now.year();
    [here - 1, here, here + 1]
        .into_iter()
        .min_by_key(|&y| distance(y))
        .unwrap_or(here)
}

fn epoch(h: &[u8], unit: EpochUnit) -> Result<Timestamp, TimeError> {
    let neg = h.first() == Some(&b'-');
    let s = usize::from(neg);
    let whole_digits = run(h, s);
    let mut e = s + whole_digits;
    let mut frac_digits: &[u8] = &[];
    if h.get(e) == Some(&b'.') {
        let f = run(h, e + 1);
        frac_digits = &h[e + 1..e + 1 + f];
        e += 1 + f;
    }
    if whole_digits == 0 || e != h.len() || whole_digits > 30 {
        return Err(TimeError::Shape("epoch"));
    }
    let digits = &h[s..s + whole_digits];
    if whole_digits <= 18 {
        epoch_small(digits, frac_digits, unit, neg)
    } else {
        epoch_wide(digits, frac_digits, unit, neg)
    }
}

/// [`epoch`] in 128-bit nanoseconds, for any count of whole digits.
fn epoch_wide(
    digits: &[u8],
    frac_digits: &[u8],
    unit: EpochUnit,
    neg: bool,
) -> Result<Timestamp, TimeError> {
    let whole: i128 = digits.iter().fold(0_i128, |n, &d| {
        n.saturating_mul(10).saturating_add(i128::from(d - b'0'))
    });
    let scale: u32 = match unit {
        EpochUnit::Seconds => 9,
        EpochUnit::Millis => 6,
        EpochUnit::Micros => 3,
        EpochUnit::Auto if whole <= 1_000_000_000_000 => 9,
        EpochUnit::Auto if whole <= 1_000_000_000_000_000 => 6,
        EpochUnit::Auto
            if !neg
                && (i128::from(EIGHTEEN_DIGITS)..1_000_000_000_000_000_000).contains(&whole) =>
        {
            return Err(TimeError::UnitNeeded);
        }
        EpochUnit::Auto if whole <= 1_000_000_000_000_000_000 => 3,
        EpochUnit::Nanos | EpochUnit::Auto => 0,
        EpochUnit::FileTime | EpochUnit::DotNetTicks => {
            unreachable!("invariant: parse_stamp reads the Windows units apart")
        }
    };
    let mut ns = whole.saturating_mul(10_i128.pow(scale));
    let kept = &frac_digits[..frac_digits.len().min(scale as usize)];
    let frac = kept
        .iter()
        .fold(0_i128, |n, &d| n * 10 + i128::from(d - b'0'));
    let pad = scale - u32::try_from(kept.len()).unwrap_or(scale);
    ns = ns.saturating_add(frac * 10_i128.pow(pad));
    Ok(Timestamp::from_nanosecond(if neg { -ns } else { ns })?)
}

/// [`epoch`] for at most 18 whole digits, which fit an `i64`, in seconds and
/// nanoseconds with no 128-bit division.
fn epoch_small(
    whole: &[u8],
    frac: &[u8],
    unit: EpochUnit,
    neg: bool,
) -> Result<Timestamp, TimeError> {
    let whole = whole
        .iter()
        .fold(0_i64, |n, &d| n * 10 + i64::from(d - b'0'));
    // Units a second holds.
    let per_second: i64 = match unit {
        EpochUnit::Seconds => 1,
        EpochUnit::Millis => 1_000,
        EpochUnit::Auto if whole <= 1_000_000_000_000 => 1,
        EpochUnit::Auto if whole <= 1_000_000_000_000_000 => 1_000,
        EpochUnit::Auto if !neg && whole >= EIGHTEEN_DIGITS => {
            return Err(TimeError::UnitNeeded);
        }
        EpochUnit::Micros | EpochUnit::Auto => 1_000_000,
        EpochUnit::Nanos => 1_000_000_000,
        EpochUnit::FileTime | EpochUnit::DotNetTicks => {
            unreachable!("invariant: parse_stamp reads the Windows units apart")
        }
    };
    let unit_ns = 1_000_000_000 / per_second;
    // A unit's fraction keeps the digits that are still whole nanoseconds.
    let kept = &frac[..frac.len().min(unit_ns.ilog10() as usize)];
    let fraction = kept
        .iter()
        .fold(0_i64, |n, &d| n * 10 + i64::from(d - b'0'))
        * 10_i64.pow(unit_ns.ilog10() - u32::try_from(kept.len()).unwrap_or(0));
    let second = whole / per_second;
    let nanos = (whole % per_second) * unit_ns + fraction;
    let (second, nanos) = if neg {
        (-second, -nanos)
    } else {
        (second, nanos)
    };
    let nanos = i32::try_from(nanos).map_err(|_| TimeError::Shape("epoch"))?;
    Ok(Timestamp::new(second, nanos)?)
}

/// The smallest 18-digit count. Under [`EpochUnit::Auto`] it reads as
/// microseconds and lands in year 5138, the size a Windows tick count has.
const EIGHTEEN_DIGITS: i64 = 100_000_000_000_000_000;

/// 100 ns ticks from 1601-01-01 to 1970-01-01.
const FILETIME_TO_UNIX: i128 = 116_444_736_000_000_000;

/// 100 ns ticks from 0001-01-01 to 1970-01-01.
const DOTNET_TICKS_TO_UNIX: i128 = 621_355_968_000_000_000;

/// Whole ASCII digits as a Windows 100 ns tick count: no sign, no fraction,
/// at most `u64::MAX`. `label` names the format in the error.
fn windows_ticks(h: &[u8], label: &'static str) -> Result<i128, TimeError> {
    if h.is_empty() || h.len() > 20 || !h.iter().all(u8::is_ascii_digit) {
        return Err(TimeError::Shape(label));
    }
    let count = num_wide(h);
    if count == 0 || count == i128::from(i64::MAX) {
        return Err(TimeError::Never);
    }
    if count > i128::from(u64::MAX) {
        return Err(TimeError::Shape(label));
    }
    Ok(count)
}

/// A FILETIME: ticks since 1601-01-01 UTC.
fn filetime(h: &[u8]) -> Result<Timestamp, TimeError> {
    let ticks = windows_ticks(h, "FILETIME")?;
    Ok(Timestamp::from_nanosecond(
        (ticks - FILETIME_TO_UNIX) * 100,
    )?)
}

/// .NET ticks: the wall clock since 0001-01-01, placed in `d`'s zone.
fn dotnet_ticks(h: &[u8], d: &TimeDefaults) -> Result<Stamp, TimeError> {
    let ticks = windows_ticks(h, ".NET tick count")?;
    let as_utc = Timestamp::from_nanosecond((ticks - DOTNET_TICKS_TO_UNIX) * 100)?;
    let wall = TimeZone::UTC.to_datetime(as_utc);
    Ok(Stamp::zone_less(d.zone.to_timestamp(wall)?))
}

/// `/Date(ms)/` or `/Date(ms+hhmm)/`, each `/` with or without its `\`.
fn ms_json_date(h: &[u8]) -> Result<Stamp, TimeError> {
    let shape = || TimeError::Shape("JSON /Date()/");
    let inner = h
        .strip_prefix(b"\\/")
        .or_else(|| h.strip_prefix(b"/"))
        .and_then(|t| t.strip_prefix(b"Date("))
        .and_then(|t| t.strip_suffix(b")\\/").or_else(|| t.strip_suffix(b")/")))
        .ok_or_else(shape)?;
    let neg = inner.first() == Some(&b'-');
    let digits = run(inner, usize::from(neg));
    let at = usize::from(neg) + digits;
    if digits == 0 || digits > 20 {
        return Err(shape());
    }
    let ms = num_wide(&inner[usize::from(neg)..at]);
    let off = match &inner[at..] {
        [] => Offset::UTC,
        zone @ [b'+' | b'-', _, _, _, _] if digits_at(zone, 1, 4) => offset(zone, 0, Some(3))?,
        _ => return Err(shape()),
    };
    let ns = (if neg { -ms } else { ms }) * 1_000_000;
    Ok(Stamp::zoned(Timestamp::from_nanosecond(ns)?, off))
}

/// ASCII digits as a number, in 128 bits for up to 20 of them. The caller
/// has checked they are digits.
fn num_wide(digits: &[u8]) -> i128 {
    digits
        .iter()
        .fold(0_i128, |n, &d| n * 10 + i128::from(d - b'0'))
}

/// The TAI64 label of 1970-01-01T00:00:00Z.
const TAI64_UNIX: i128 = (1 << 62) + 10;

fn tai64n(h: &[u8]) -> Result<Timestamp, TimeError> {
    let hex = h.strip_prefix(b"@").unwrap_or(h);
    let value = |digits: &[u8]| {
        digits.iter().try_fold(0_i128, |n, &b| {
            Some(n * 16 + i128::from(char::from(b).to_digit(16)?))
        })
    };
    let (secs, nanos) = match (hex.len(), hex.split_at_checked(16)) {
        (24, Some((secs, nanos))) => (value(secs), value(nanos)),
        _ => (None, None),
    };
    match (secs, nanos) {
        (Some(secs), Some(nanos)) if nanos < 1_000_000_000 => Ok(Timestamp::from_nanosecond(
            (secs - TAI64_UNIX) * 1_000_000_000 + nanos,
        )?),
        _ => Err(TimeError::Shape("TAI64N")),
    }
}

#[cfg(test)]
mod tests;