use jiff::Timestamp;
use jiff::fmt::strtime::{self, BrokenDownTime};
use jiff::tz::{Offset, TimeZone};
use proptest::prelude::{ProptestConfig, Strategy, TestCaseError, prop, prop_oneof, proptest};
use super::{
Clock, JavaPattern, MAX_READINGS, Node, TextZone, Tok, Year, ZoneText, Zulu, civil, text_zone,
tree,
};
use crate::time::{Stamp, TimeDefaults, TimeError, num, run};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(in crate::time) struct Reading {
pieces: Vec<Piece>,
year: Year,
clock: Clock,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Piece {
Strtime(String),
Zone(ZoneText),
Skip {
min: usize,
max: usize,
},
Nanos,
}
pub(in crate::time) fn build(pattern: &str) -> Result<Vec<Reading>, TimeError> {
let refuse = |part: String| TimeError::Pattern {
pattern: pattern.to_owned(),
part,
};
let nodes = tree(pattern).map_err(|part| refuse(part.to_owned()))?;
let sequences = expand(&nodes, vec![Vec::new()])
.ok_or_else(|| refuse(format!("more than {MAX_READINGS} optional readings")))?;
let mut readings: Vec<Reading> = Vec::with_capacity(sequences.len());
for sequence in &sequences {
let reading = lower(sequence).map_err(refuse)?;
if !readings.contains(&reading) {
readings.push(reading);
}
}
Ok(readings)
}
pub(in crate::time) fn parse(
readings: &[Reading],
input: &[u8],
d: &TimeDefaults,
) -> Result<Stamp, TimeError> {
let mut last = TimeError::Shape("Java pattern");
for reading in readings {
match reading.parse(input, d) {
Ok(ts) => return Ok(ts),
Err(e) => last = e,
}
}
Err(last)
}
impl Reading {
fn parse(&self, input: &[u8], d: &TimeDefaults) -> Result<Stamp, TimeError> {
let mut tm = BrokenDownTime::default();
let mut zone = None;
if let [Piece::Strtime(fmt)] = self.pieces.as_slice() {
tm = strtime::parse(fmt, input)?;
} else {
let mut rest = input;
for piece in &self.pieces {
let used = match piece {
Piece::Strtime(fmt) => {
let (part, used) = BrokenDownTime::parse_prefix(fmt, rest)?;
merge(&mut tm, &part)?;
used
}
Piece::Zone(kind) => {
let (z, used) = text_zone(rest, *kind).ok_or(TimeError::Shape("zone"))?;
zone = Some(z);
used
}
Piece::Skip { min, max } => {
let n = run(rest, 0).min(*max);
if n < *min {
return Err(TimeError::Shape("Java pattern"));
}
n
}
Piece::Nanos => {
let n = run(rest, 0).min(9);
if n == 0 {
return Err(TimeError::Shape("Java pattern"));
}
let ns = i32::try_from(num(&rest[..n]))
.map_err(|_| TimeError::Shape("Java pattern"))?;
tm.set_subsec_nanosecond(Some(ns))?;
n
}
};
rest = &rest[used..];
}
if !rest.is_empty() {
return Err(TimeError::Shape("Java pattern"));
}
}
let dt = civil(&mut tm, input, d, self.year, self.clock)?;
Ok(match zone {
Some(TextZone::Fixed(off)) => Stamp::zoned(off.to_timestamp(dt)?, off),
Some(TextZone::Named(name)) => {
let zoned = dt.to_zoned_datetime(TimeZone::get(name)?)?;
Stamp::zoned(zoned.timestamp(), zoned.offset())
}
None => Stamp::zone_less(d.zone.to_timestamp(dt)?),
})
}
}
fn merge(into: &mut BrokenDownTime, from: &BrokenDownTime) -> Result<(), jiff::Error> {
if from.year().is_some() {
into.set_year(from.year())?;
}
if from.month().is_some() {
into.set_month(from.month())?;
}
if from.day().is_some() {
into.set_day(from.day())?;
}
if from.day_of_year().is_some() {
into.set_day_of_year(from.day_of_year())?;
}
if from.meridiem().is_some() {
into.set_meridiem(from.meridiem());
}
if from.hour().is_some() {
into.set_hour(from.hour())?;
}
if from.minute().is_some() {
into.set_minute(from.minute())?;
}
if from.second().is_some() {
into.set_second(from.second())?;
}
if from.subsec_nanosecond().is_some() {
into.set_subsec_nanosecond(from.subsec_nanosecond())?;
}
Ok(())
}
fn expand(nodes: &[Node], prefixes: Vec<Vec<Tok>>) -> Option<Vec<Vec<Tok>>> {
let mut seqs = prefixes;
for node in nodes {
match node {
Node::Tok(t) => seqs.iter_mut().for_each(|s| s.push(*t)),
Node::Optional(body) => {
let options = expand(body, vec![Vec::new()])?;
let total = seqs.len().checked_mul(options.len() + 1)?;
if total > MAX_READINGS {
return None;
}
let mut next = Vec::with_capacity(total);
for s in seqs {
for o in &options {
let mut with = s.clone();
with.extend_from_slice(o);
next.push(with);
}
next.push(s);
}
seqs = next;
}
}
}
Some(seqs)
}
fn lower(toks: &[Tok]) -> Result<Reading, String> {
let has = |set: &[char]| {
toks.iter()
.any(|t| matches!(t, Tok::Letter(c, _) if set.contains(c)))
};
let calendar_year = has(&['y', 'u']);
let week = has(&['Y']);
if week && calendar_year {
return Err("letter Y beside y or u".to_owned());
}
let week_only = |c: char| "YMLdDwWFHkmsS".contains(c);
if let Some(Tok::Letter(c, n)) = toks
.iter()
.find(|t| week && matches!(t, Tok::Letter(c, _) if !week_only(*c)))
{
return Err(format!("letter {} beside Y", c.to_string().repeat(*n)));
}
let meridiem = has(&['a']);
let mut pieces = Vec::new();
let mut fmt = String::new();
for &tok in toks {
let (c, n) = match tok {
Tok::Lit('%') => {
fmt.push_str("%%");
continue;
}
Tok::Lit(c) => {
fmt.push(c);
continue;
}
Tok::Letter(c, n) => (c, n),
};
let piece = match (c, n) {
('M' | 'L' | 'd' | 'D' | 'w' | 'W' | 'F', _) if week => Some(if n == 1 {
Piece::Skip { min: 1, max: 10 }
} else {
Piece::Skip { min: n, max: n }
}),
('n' | 'N', _) => Some(Piece::Nanos),
('z' | 'v' | 'V', _) | ('Z', 4) => Some(Piece::Zone(ZoneText::Name)),
('X', 1..=5) | ('Z', 5) => Some(Piece::Zone(ZoneText::Offset(Zulu::Accepted))),
('x', 1..=5) | ('Z', 1..=3) => Some(Piece::Zone(ZoneText::Offset(Zulu::Refused))),
_ => None,
};
if let Some(piece) = piece {
if !fmt.is_empty() {
pieces.push(Piece::Strtime(std::mem::take(&mut fmt)));
}
pieces.push(piece);
continue;
}
fmt.push_str(match (c, n) {
('G', 1..=3) => "AD",
('y' | 'u' | 'Y', 2) => "%y",
('y' | 'u' | 'Y', _) => "%Y",
('M' | 'L', 1 | 2) => "%m",
('M' | 'L', 3) => "%b",
('M' | 'L', 4) => "%B",
('d', 1 | 2) => "%d",
('D', 1..=3) => "%j",
('E', 1..=3) => "%a",
('E', 4) => "%A",
('a', 1) => "%p",
('h', 1 | 2) if meridiem => "%I",
('H' | 'k' | 'h', 1 | 2) => "%H",
('m', 1 | 2) => "%M",
('s', 1 | 2) => "%S",
('S', 1..=9) => "%f",
_ => return Err(format!("letter {}", c.to_string().repeat(n))),
});
}
if !fmt.is_empty() {
pieces.push(Piece::Strtime(fmt));
}
let hour = has(&['H', 'k', 'h']);
let (minute, second, fraction) = (has(&['m']), has(&['s']), has(&['S', 'n', 'N']));
let gap = hour && (second || fraction) && !(minute && second);
let clock = if gap || (has(&['h']) && !meridiem) {
Clock::Dropped
} else {
Clock::Kept
};
let year = if week {
Year::WeekBased
} else if toks
.iter()
.any(|t| matches!(t, Tok::Letter('y' | 'u', n) if *n >= 4))
{
Year::Wide
} else if calendar_year {
Year::Plain
} else {
Year::Absent
};
Ok(Reading {
pieces,
year,
clock,
})
}
type Pieces = &'static [(&'static str, &'static [&'static str])];
const PIECES: Pieces = &[
("yyyy", &["2026", "0999", "26", "+2026", "-0044"]),
("yy", &["26", "99", "2026"]),
("uuuu", &["2024", "24"]),
("y", &["2026"]),
("MM", &["11", "1", "13", " 7"]),
("M", &["7", "12", "0"]),
("MMM", &["Nov", "jan", "Foo", "No"]),
("MMMM", &["November", "may", "Mayday"]),
("dd", &["30", "05", " 5", "32"]),
("d", &["5", "31", "29"]),
("DDD", &["060", "366", "367"]),
("EEE", &["Mon", "tue", "Xyz"]),
("EEEE", &["Monday", "friday", "Fri"]),
("HH", &["10", "00", "23", "24"]),
("H", &["7"]),
("kk", &["10"]),
("hh", &["04", "12", "13", "00"]),
("h", &["4", "11"]),
("a", &["PM", "am", "XM", "P"]),
("mm", &["00", "59", "60"]),
("ss", &["01", "60", "61"]),
("SSS", &["123", "5", "1234567890"]),
("S", &["7"]),
("n", &["9196243", "x"]),
("XXX", &["+11:00", "Z", "-0530", "+19:00"]),
("X", &["Z", "+05"]),
("xx", &["+1100", "Z"]),
("Z", &["+0000", "-0500"]),
("ZZZZ", &["GMT+08:00", "UTC"]),
("z", &["UTC", "AEST", "GMT+01:00", "XYZ"]),
("VV", &["+09:00", "UTC"]),
("G", &["AD", "BC"]),
("YYYY", &["2020"]),
("'T'", &["T", "t"]),
("''", &["'"]),
("'%H'", &["%H"]),
("-", &["-", "/"]),
(":", &[":", ""]),
(" ", &[" ", " ", ""]),
(".", &["."]),
(",", &[","]),
("/", &["/"]),
];
const WEEK_PIECES: Pieces = &[
("YYYY", &["2020", "20"]),
("YY", &["20"]),
("MM", &["01", "1"]),
("M", &["1", "123"]),
("MMM", &["003", "Jan"]),
("MMMMM", &["01234"]),
("dd", &["16", "6"]),
("d", &["6", "16"]),
("DDD", &["060"]),
("ww", &["05", "5"]),
("HH", &["08"]),
("kk", &["08"]),
("mm", &["00"]),
("ss", &["31"]),
("SSS", &["123"]),
("yyyy", &["2020"]),
("EEE", &["Mon"]),
("-", &["-"]),
(" ", &[" "]),
(":", &[":"]),
];
#[derive(Debug, Clone)]
enum Gen {
Piece(&'static str, &'static [&'static str]),
Section(Vec<Self>),
}
fn patterns(pieces: Pieces) -> impl Strategy<Value = Vec<Gen>> {
let leaf = prop::sample::select(pieces).prop_map(|(piece, texts)| Gen::Piece(piece, texts));
let node = leaf.prop_recursive(3, 16, 3, |inner| {
prop::collection::vec(inner, 1..4).prop_map(Gen::Section)
});
prop::collection::vec(node, 1..7)
}
fn write(nodes: &[Gen], out: &mut String) {
for node in nodes {
match node {
Gen::Piece(piece, _) => out.push_str(piece),
Gen::Section(body) => {
out.push('[');
write(body, out);
out.push(']');
}
}
}
}
fn render(nodes: &[Gen], picks: &mut impl Iterator<Item = usize>, out: &mut String) {
for node in nodes {
let pick = picks.next().unwrap_or(0);
match node {
Gen::Piece(_, texts) => {
out.push_str(texts[(pick % (texts.len() + 2)).saturating_sub(2)]);
}
Gen::Section(body) if !pick.is_multiple_of(3) => render(body, picks, out),
Gen::Section(_) => {}
}
}
}
fn mutate(text: &mut String, picks: &mut impl Iterator<Item = usize>) {
let (kind, at) = (picks.next().unwrap_or(0), picks.next().unwrap_or(0));
let Some((i, _)) = text.char_indices().nth(at % text.chars().count().max(1)) else {
return;
};
match kind % 8 {
0 => {
text.remove(i);
}
1 => text.insert(i, '1'),
2 => text.insert(i, ' '),
_ => {}
}
}
const ROWS: &[(&str, &str)] = &[
(
"[EEE ]MMM [ ]d[ yyyy] HH:mm:ss[.SSS][ z]",
"Wed Oct 10 2018 12:34:56.5 AEST",
),
(
"yyyy-MM-dd HH:mm:ss[.SSSSSSSSS][.SSSSSSSS][.SSSSSSS][.SSSSSS][.SSSSS][.SSSS][.SSS][.SS][.S]X",
"2016-02-29 10:42:23.125-0700",
),
("yyyy-MM-dd[[ HH]:mm]", "2026-01-15 10:30"),
("yyyy-MM-dd[ HH", "2026-01-15 10"),
("yyyy-MM-dd hh:mm[ a]", "2026-11-30 04:12 PM"),
("[a ]hh:mm", "PM 04:12"),
("[YYYY-]MM-dd HH:mm", "2020-01-16 08:00"),
("MM-dd[ YYYY] HH:mm", "01-16 2020 08:00"),
(
"yyyy-MM-dd'T'HH:mm:ss[.SSSSSS]x",
"2024-01-15T10:30:00.123456+1100",
),
];
proptest! {
#![proptest_config(ProptestConfig::with_cases(4_000))]
#[test]
fn one_pass_reads_what_trying_every_reading_reads(
nodes in prop_oneof![patterns(PIECES), patterns(WEEK_PIECES)],
picks in prop::collection::vec(0_usize..1000, 80),
year in prop::option::of(1990_i16..2040),
hours in -12_i8..=14,
) {
let mut pattern = String::new();
write(&nodes, &mut pattern);
let (walk, readings) = match (JavaPattern::build(&pattern), build(&pattern)) {
(Ok(walk), Ok(readings)) => (walk, readings),
(
Err(TimeError::Pattern { part: got, .. }),
Err(TimeError::Pattern { part: want, .. }),
) => {
proptest::prop_assert_eq!(got, want, "{}", pattern);
return Ok(());
}
(got, want) => {
return Err(TestCaseError::fail(format!("{pattern}: {got:?}, want {want:?}")));
}
};
let mut picks = picks.into_iter();
let mut text = String::new();
render(&nodes, &mut picks, &mut text);
mutate(&mut text, &mut picks);
let d = TimeDefaults {
zone: TimeZone::fixed(Offset::from_hours(hours).unwrap()),
year,
now: Some(Timestamp::from_second(1_764_460_800).unwrap()),
..TimeDefaults::default()
};
let got = walk.parse(text.as_bytes(), &d).ok();
let want = parse(&readings, text.as_bytes(), &d).ok();
proptest::prop_assert_eq!(got, want, "{} {:?}", pattern, text);
}
#[test]
fn one_pass_reads_the_table_patterns_as_trying_every_reading_does(
row in 0..ROWS.len(),
picks in prop::collection::vec(0_usize..1000, 6),
hours in -12_i8..=14,
) {
let (pattern, hit) = ROWS[row];
let walk = JavaPattern::build(pattern).unwrap();
let readings = build(pattern).unwrap();
let mut picks = picks.into_iter();
let mut text = hit.to_owned();
for _ in 0..3 {
mutate(&mut text, &mut picks);
}
let d = TimeDefaults {
zone: TimeZone::fixed(Offset::from_hours(hours).unwrap()),
year: Some(2026),
now: None,
..TimeDefaults::default()
};
for input in [hit, text.as_str()] {
let got = walk.parse(input.as_bytes(), &d).ok();
let want = parse(&readings, input.as_bytes(), &d).ok();
proptest::prop_assert_eq!(got, want, "{} {:?}", pattern, input);
}
}
}