use super::GrokError;
#[derive(Clone, Copy)]
struct Dir {
free: &'static str,
fixed: Option<&'static str>,
digit: bool,
empty: bool,
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]");
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}");
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,
};
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",
];
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]");
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),
Space,
Names(&'static [&'static str]),
Dir(Dir),
}
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}"))
}
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
}
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;
}
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::*;
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;
#[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
);
});
}
}
#[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:?}");
}
}
}
}
}