grippo 0.1.2

Parse, match and scrub data at scale.
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
// Project:   grippo
// File:      src/grok/date.rs
// Purpose:   A grok matcher built from a strptime format
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A regex for the timestamps a strptime format reads.
//!
//! jiff's strptime reads a number greedily, up to its width, and never gives
//! a digit back. So a number with a digit after it is matched at its full
//! width, and a directive with no fixed width is refused there.

use super::GrokError;

/// One directive's regex.
#[derive(Clone, Copy)]
struct Dir {
    /// The regex where no digit can follow.
    free: &'static str,
    /// The regex where a digit can follow, or `None` when there is none.
    fixed: Option<&'static str>,
    /// It can start with a digit.
    digit: bool,
    /// It can match nothing.
    empty: bool,
    /// jiff reads it only at the end of the input.
    last: bool,
}

const fn num(free: &'static str, fixed: &'static str) -> Dir {
    Dir {
        free,
        fixed: Some(fixed),
        digit: true,
        empty: false,
        last: false,
    }
}

const fn signed(re: &'static str) -> Dir {
    Dir {
        free: re,
        fixed: Some(re),
        digit: false,
        empty: false,
        last: false,
    }
}

const DAY: Dir = num("3[01]|[12][0-9]|0?[1-9]", "3[01]|[12][0-9]|0[1-9]");
const DAY_SPACE: Dir = num("3[01]|[12][0-9]|0?[1-9]| [1-9]", "3[01]|[12][0-9]|0[1-9]");
const MONTH: Dir = num("1[0-2]|0?[1-9]", "1[0-2]|0[1-9]");
const HOUR: Dir = num("2[0-3]|[01]?[0-9]", "2[0-3]|[01][0-9]");
const HOUR_SPACE: Dir = num("2[0-3]|[01]?[0-9]| [0-9]", "2[0-3]|[01][0-9]");
const HOUR12: Dir = num("1[0-2]|0?[1-9]", "1[0-2]|0[1-9]");
const HOUR12_SPACE: Dir = num("1[0-2]|0?[1-9]| [1-9]", "1[0-2]|0[1-9]");
const MINUTE: Dir = num("[0-5]?[0-9]", "[0-5][0-9]");
// jiff reads a leap second, 60, as 59.
const SECOND: Dir = num("60|[0-5]?[0-9]", "60|[0-5][0-9]");
const DAY_OF_YEAR: Dir = num(
    "36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0?[1-9][0-9]|0{0,2}[1-9]",
    "36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]",
);
const WEEK: Dir = num("5[0-3]|[0-4]?[0-9]", "5[0-3]|[0-4][0-9]");
const ISO_WEEK: Dir = num("5[0-3]|[1-4][0-9]|0?[1-9]", "5[0-3]|[1-4][0-9]|0[1-9]");
const WEEKDAY_MON: Dir = num("[1-7]", "[1-7]");
const WEEKDAY_SUN: Dir = num("[0-6]", "[0-6]");
const YEAR: Dir = num("[+-]?[0-9]{1,4}", "[+-]?[0-9]{4}");
const YEAR2: Dir = num("[0-9]{1,2}", "[0-9]{2}");
const CENTURY: Dir = num("[+-]?[0-9]{1,2}", "[+-]?[0-9]{2}");
// Eleven digits reach the year 5138, inside jiff's range either side of 1970.
const EPOCH: Dir = Dir {
    fixed: None,
    ..num("[+-]?[0-9]{1,11}", "")
};
const FRACTION: Dir = Dir {
    fixed: None,
    ..num("[0-9]{1,9}", "")
};
const DOT_FRACTION: Dir = Dir {
    free: r"(?:\.[0-9]{1,9})?",
    fixed: None,
    digit: false,
    empty: true,
    last: false,
};
// jiff folds only ASCII case, so `(?i)` would let `\u{17f}` stand for `s`.
const AMPM: &[&str] = &["am", "pm"];
const MONTH_ABBR: &[&str] = &[
    "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
];
const MONTH_FULL: &[&str] = &[
    "january",
    "february",
    "march",
    "april",
    "may",
    "june",
    "july",
    "august",
    "september",
    "october",
    "november",
    "december",
];
const WEEKDAY_ABBR: &[&str] = &["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
const WEEKDAY_FULL: &[&str] = &[
    "sunday",
    "monday",
    "tuesday",
    "wednesday",
    "thursday",
    "friday",
    "saturday",
];
// jiff reads seconds after `+HHMM` whenever a digit follows.
const OFFSET: Dir = Dir {
    fixed: None,
    ..signed("[+-](?:[01][0-9]|2[0-5])[0-5][0-9](?:[0-5][0-9])?")
};
const OFFSET_COLON: Dir = signed("[+-](?:[01][0-9]|2[0-5]):[0-5][0-9](?::[0-5][0-9])?");
const OFFSET_COLON2: Dir = signed("[+-](?:[01][0-9]|2[0-5]):[0-5][0-9]:[0-5][0-9]");
// jiff refuses anything but `:` straight after the hours.
const OFFSET_COLON3: Dir = Dir {
    last: true,
    ..signed("[+-](?:[01][0-9]|2[0-5])(?::[0-5][0-9](?::[0-5][0-9])?)?")
};

#[derive(Clone, Copy)]
enum Item {
    Literal(char),
    /// Whitespace in the format, which jiff reads as any run of it.
    Space,
    /// One of these words, in any ASCII case.
    Names(&'static [&'static str]),
    Dir(Dir),
}

/// A regex matching the text jiff's strptime reads for `format`, in jiff's
/// dialect (`TimeFormat::strptime` translates others). Numbers are held to
/// their ranges, a month to 1-12, so `99/99` doesn't match `%m/%d`.
///
/// # Errors
///
/// [`GrokError::Date`] for a directive with no matcher: the locale forms
/// (`%c`, `%x`, `%X`, `%r`), a zone name (`%Z`, `%Q`), a width on anything
/// but a fraction, `%s`, `%f` or `%z` with a digit straight after, and
/// `%:::z` before the end.
pub fn date_pattern(format: &str) -> Result<String, GrokError> {
    let mut items = Vec::new();
    read(format, format, &mut items)?;
    let mut out = String::with_capacity(format.len() * 16);
    for (i, item) in items.iter().enumerate() {
        match *item {
            Item::Literal(c) => regex_syntax::escape_into(c.encode_utf8(&mut [0; 4]), &mut out),
            Item::Space => out.push_str("[\t ]+"),
            Item::Names(names) => {
                out.push_str("(?:");
                for (n, name) in names.iter().enumerate() {
                    if n > 0 {
                        out.push('|');
                    }
                    for b in name.bytes().map(char::from) {
                        out.extend(['[', b.to_ascii_uppercase(), b, ']']);
                    }
                }
                out.push(')');
            }
            Item::Dir(d) => {
                if d.last && i + 1 < items.len() {
                    return Err(fail(format, "%:::z has to end the format"));
                }
                let re = if digit_next(&items[i + 1..]) {
                    d.fixed
                        .ok_or_else(|| fail(format, "a digit straight after %s, %f or %z"))?
                } else {
                    d.free
                };
                out.push_str("(?:");
                out.push_str(re);
                out.push(')');
            }
        }
    }
    Ok(out)
}

fn fail(format: &str, why: &str) -> GrokError {
    GrokError::Date(format!("{format:?}: {why}"))
}

/// The next item that can't match nothing can start with a digit.
fn digit_next(rest: &[Item]) -> bool {
    for item in rest {
        match item {
            Item::Literal(c) => return c.is_ascii_digit(),
            Item::Space | Item::Names(_) => return false,
            Item::Dir(d) if d.empty => {}
            Item::Dir(d) => return d.digit,
        }
    }
    false
}

/// `format` as items, with `%D`, `%F`, `%R` and `%T` spelled out.
fn read(whole: &str, format: &str, items: &mut Vec<Item>) -> Result<(), GrokError> {
    let mut chars = format.chars().peekable();
    while let Some(c) = chars.next() {
        if c != '%' {
            items.push(if c.is_ascii_whitespace() {
                Item::Space
            } else {
                Item::Literal(c)
            });
            continue;
        }
        // Flags change only how jiff writes a number, never what it reads.
        while chars
            .next_if(|c| matches!(c, '-' | '_' | '0' | '^' | '#'))
            .is_some()
        {}
        let mut width = false;
        while chars.next_if(char::is_ascii_digit).is_some() {
            width = true;
        }
        let mut colons = 0;
        while chars.next_if_eq(&':').is_some() {
            colons += 1;
        }
        let dot = chars.next_if_eq(&'.').is_some();
        if dot {
            while chars.next_if(char::is_ascii_digit).is_some() {}
        }
        let d = chars.next().ok_or_else(|| fail(whole, "a % at the end"))?;
        let dir = match (d, colons, dot) {
            ('f', 0, true) => DOT_FRACTION,
            ('f' | 'N', 0, false) => FRACTION,
            (_, _, true) => return Err(fail(whole, "only %.f takes a dot")),
            (_, _, false) if width => return Err(fail(whole, "a width on a number")),
            ('z', 0, _) => OFFSET,
            ('z', 1, _) => OFFSET_COLON,
            ('z', 2, _) => OFFSET_COLON2,
            ('z', 3, _) => OFFSET_COLON3,
            (_, 1.., _) => return Err(fail(whole, "colons on a directive other than %z")),
            ('%', ..) => {
                items.push(Item::Literal('%'));
                continue;
            }
            ('n' | 't', ..) => {
                items.push(Item::Space);
                continue;
            }
            ('D', ..) => {
                read(whole, "%m/%d/%y", items)?;
                continue;
            }
            ('F', ..) => {
                read(whole, "%Y-%m-%d", items)?;
                continue;
            }
            ('R', ..) => {
                read(whole, "%H:%M", items)?;
                continue;
            }
            ('T', ..) => {
                read(whole, "%H:%M:%S", items)?;
                continue;
            }
            ('d', ..) => DAY,
            ('e', ..) => DAY_SPACE,
            ('m', ..) => MONTH,
            ('H', ..) => HOUR,
            ('k', ..) => HOUR_SPACE,
            ('I', ..) => HOUR12,
            ('l', ..) => HOUR12_SPACE,
            ('M', ..) => MINUTE,
            ('S', ..) => SECOND,
            ('j', ..) => DAY_OF_YEAR,
            ('U' | 'W', ..) => WEEK,
            ('V', ..) => ISO_WEEK,
            ('u', ..) => WEEKDAY_MON,
            ('w', ..) => WEEKDAY_SUN,
            ('Y' | 'G', ..) => YEAR,
            ('y' | 'g', ..) => YEAR2,
            ('C', ..) => CENTURY,
            ('s', ..) => EPOCH,
            ('p' | 'P', ..) => {
                items.push(Item::Names(AMPM));
                continue;
            }
            ('b' | 'h', ..) => {
                items.push(Item::Names(MONTH_ABBR));
                continue;
            }
            ('B', ..) => {
                items.push(Item::Names(MONTH_FULL));
                continue;
            }
            ('a', ..) => {
                items.push(Item::Names(WEEKDAY_ABBR));
                continue;
            }
            ('A', ..) => {
                items.push(Item::Names(WEEKDAY_FULL));
                continue;
            }
            (other, ..) => return Err(fail(whole, &format!("%{other} has no matcher"))),
        };
        items.push(Item::Dir(dir));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Formats held against jiff, with lines that hit and lines that miss.
    const FORMATS: &[(&str, &[&str], &[&str])] = &[
        (
            "%Y-%m-%dT%H:%M:%S%.f%:z",
            &["2026-11-27T18:30:00.123456+11:00", "2026-1-7T8:3:0-05:00"],
            &["2026-13-27T18:30:00+11:00", "2026-11-27T18:30:00+1100"],
        ),
        (
            "%d/%b/%Y:%H:%M:%S %z",
            &["27/Nov/2026:18:30:00 +1100", "27/nov/2026:18:30:00  -0530"],
            &["27/Nov/2026:18:30:00 +11:00", "32/Nov/2026:18:30:00 +1100"],
        ),
        (
            "%b %e %H:%M:%S",
            &["Nov  7 08:03:00", "Nov 27 18:30:60"],
            &["Nov 7 08:61:00"],
        ),
        (
            "%a, %d %b %Y %T %z",
            &["Fri, 27 Nov 2026 18:30:00 +1100"],
            &["Fry, 27 Nov 2026 18:30:00 +1100"],
        ),
        (
            "%Y%m%d%H%M%S",
            &["20261127183000"],
            &["20261127186000", "20261327183000"],
        ),
        (
            "%m/%d/%y %I:%M:%S %p",
            &["11/27/26 06:30:00 PM", "1/7/26 6:30:00 am"],
            &["11/27/26 13:30:00 PM"],
        ),
        (
            "%A, %B %d, %Y %l:%M %P",
            &["Friday, November 27, 2026  6:30 pm"],
            &["Friday, Nov 27, 2026 6:30 pm"],
        ),
        ("%s", &["1795768200", "-86400"], &["1795768200.5"]),
        ("%s.%f", &["1795768200.123"], &["1795768200."]),
        (
            "%F %T%.f",
            &["2026-11-27 18:30:00", "2026-11-27 18:30:00.5"],
            &["2026-11-27 18:30:00."],
        ),
        ("%D %R", &["11/27/26 18:30"], &["11/27/2026 18:30"]),
        ("%k:%M:%S", &[" 8:30:00", "18:30:00"], &["24:30:00"]),
        (
            "%C%y-%j",
            &["2026-331", "2026-001", "2026-366"],
            &["2026-367", "2026-000"],
        ),
        ("%G-W%V-%u", &["2026-W48-5"], &["2026-W54-5", "2026-W48-8"]),
        ("%Y %U %W %w", &["2026 47 48 5"], &["2026 54 48 5"]),
        ("%H%M%S%.f", &["183000", "183000.25"], &["186000"]),
        (
            "%Y-%m-%d %H:%M:%S%::z",
            &["2026-11-27 18:30:00+11:00:00"],
            &["2026-11-27 18:30:00+11:00"],
        ),
        (
            "%Y-%m-%dT%H:%M%:::z",
            &["2026-11-27T18:30+11", "2026-11-27T18:30+05:30"],
            &["2026-11-27T18:30+1100"],
        ),
        ("%d%m%Y", &["27112026"], &["27132026"]),
        ("100%% at %Y", &["100% at 2026"], &["100 at 2026"]),
    ];

    fn whole(format: &str) -> regex::Regex {
        let re = date_pattern(format).unwrap();
        regex::Regex::new(&format!("^(?:{re})$")).unwrap()
    }

    #[test]
    fn a_format_matches_its_hits_and_none_of_its_misses() {
        for (format, hits, misses) in FORMATS {
            let re = whole(format);
            for hit in *hits {
                assert!(re.is_match(hit), "{format} should match {hit:?}");
            }
            for miss in *misses {
                assert!(!re.is_match(miss), "{format} matched {miss:?}");
            }
        }
    }

    #[test]
    fn a_directive_with_no_matcher_is_refused() {
        for format in [
            "%Z", "%c", "%x", "%X", "%r", "%Q", "%s%H", "%f%M", "%z%H", "%.f%S", "%:::z %H", "%5Y",
            "%Y%", "%:H", "%.3S", "%E",
        ] {
            assert!(
                matches!(date_pattern(format), Err(GrokError::Date(_))),
                "{format} built"
            );
        }
    }

    #[cfg(feature = "time")]
    mod held_to_jiff {
        use super::*;
        use jiff::Timestamp;
        use jiff::fmt::strtime::{self, BrokenDownTime};
        use jiff::tz::Offset;
        use proptest::prelude::*;
        use proptest::string::string_regex;

        /// Every text the regex matches, jiff reads.
        #[test]
        fn jiff_reads_every_match() {
            for (format, _, _) in FORMATS {
                let re = date_pattern(format).unwrap();
                proptest!(ProptestConfig::with_cases(256), |(text in string_regex(&re).unwrap())| {
                    prop_assert!(
                        strtime::parse(format, &text).is_ok(),
                        "{} matched {:?}, which jiff refuses", format, text
                    );
                });
            }
        }

        /// Every instant jiff writes in the format, the regex matches.
        #[test]
        fn the_regex_matches_what_jiff_writes() {
            for (format, _, _) in FORMATS {
                let re = whole(format);
                for k in 0..500_i64 {
                    let second = -2_208_988_800 + k * 12_623_401;
                    let nanos = i32::try_from((k * 7_919_123) % 1_000_000_000).unwrap();
                    let offset = i32::try_from(((k * 37) % 105 - 48) * 15 * 60).unwrap();
                    let offset = Offset::from_seconds(offset).unwrap();
                    let at = Timestamp::new(second, nanos).unwrap();
                    let mut tm = BrokenDownTime::from(offset.to_datetime(at));
                    tm.set_offset(Some(offset));
                    tm.set_timestamp(Some(at));
                    let text = tm.to_string(format).unwrap();
                    assert!(re.is_match(&text), "{format} missed {text:?}");
                }
            }
        }
    }
}