use jiff::Timestamp;
use jiff::civil::{Date, DateTime, Time};
use jiff::fmt::strtime::{BrokenDownTime, Meridiem};
use jiff::tz::{Offset, TimeZone};
use super::{Stamp, TimeDefaults, TimeError, nanos, num, run, year_for};
#[cfg(test)]
pub(super) mod oracle;
const MAX_READINGS: usize = 1024;
const FIXED_ZONES: &[(&str, i32)] = &[
("ACDT", 630),
("ACST", 570),
("AEDT", 660),
("AEST", 600),
("AKDT", -480),
("AKST", -540),
("AWST", 480),
("BST", 60),
("CDT", -300),
("CEST", 120),
("CET", 60),
("EDT", -240),
("EEST", 180),
("EET", 120),
("EST", -300),
("HKT", 480),
("HST", -600),
("JST", 540),
("KST", 540),
("MDT", -360),
("MSK", 180),
("MST", -420),
("NZDT", 780),
("NZST", 720),
("PDT", -420),
("PST", -480),
("SGT", 480),
("WEST", 60),
("WET", 0),
];
const SHARED_ZONES: &[(&str, &str)] = &[
("ACT", "Australia/Darwin"),
("AET", "Australia/Sydney"),
("AGT", "America/Argentina/Buenos_Aires"),
("ART", "Africa/Cairo"),
("AST", "America/Anchorage"),
("BET", "America/Sao_Paulo"),
("CAT", "Africa/Harare"),
("CNT", "America/St_Johns"),
("CST", "America/Chicago"),
("CTT", "Asia/Shanghai"),
("EAT", "Africa/Addis_Ababa"),
("ECT", "Europe/Paris"),
("IET", "America/Indiana/Indianapolis"),
("IST", "Asia/Kolkata"),
("MIT", "Pacific/Apia"),
("NET", "Asia/Yerevan"),
("NST", "Pacific/Auckland"),
("PLT", "Asia/Karachi"),
("PNT", "America/Phoenix"),
("PRT", "America/Puerto_Rico"),
("SST", "Pacific/Guadalcanal"),
("VST", "Asia/Ho_Chi_Minh"),
];
const MONTHS: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const WEEKDAYS: [&str; 7] = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JavaPattern {
pattern: String,
ops: Vec<Op>,
print: Vec<Tok>,
base: Facts,
split: Option<Split>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Split {
letter: Facts,
without: Vec<Step>,
}
impl JavaPattern {
#[must_use]
pub fn pattern(&self) -> &str {
&self.pattern
}
#[cfg(test)]
pub(super) fn readings_len(&self) -> usize {
oracle::build(&self.pattern).map_or(0, |readings| readings.len())
}
pub(super) fn build(pattern: &str, exact: bool) -> Result<Self, TimeError> {
let refuse = |part: String| TimeError::Pattern {
pattern: pattern.to_owned(),
part,
};
let nodes = tree(pattern).map_err(|part| refuse(part.to_owned()))?;
if readings(&nodes).is_none() {
return Err(refuse(format!(
"more than {MAX_READINGS} optional readings"
)));
}
let mut fullest = Vec::new();
tokens(&nodes, None, &mut fullest);
check(&fullest).map_err(refuse)?;
let mut without_week = Vec::new();
tokens(&nodes, Some('Y'), &mut without_week);
check(&without_week).map_err(refuse)?;
let all = facts(fullest.iter().copied());
let base = direct(&nodes);
let letter = if all.has(Facts::WEEK_YEAR) {
Facts::WEEK_YEAR
} else {
Facts::MERIDIEM
};
let without = Ctx {
exact,
..Ctx::default()
};
let with = Ctx {
week: letter == Facts::WEEK_YEAR,
meridiem: letter == Facts::MERIDIEM,
exact,
};
let ctx = if base.has(letter) {
[with; 2]
} else if all.has(letter) {
[with, without]
} else {
[without; 2]
};
let (mut ops, mut without) = (Vec::new(), Vec::new());
compile(&nodes, ctx, &mut ops, &mut without);
let differs = ops
.iter()
.zip(&without)
.any(|(op, other)| matches!(op, Op::Step(step) if step != other));
Ok(Self {
pattern: pattern.to_owned(),
ops,
print: fullest,
base,
split: differs.then_some(Split { letter, without }),
})
}
pub(super) fn print(&self, ts: Timestamp, zone: &TimeZone, out: &mut String) {
let info = zone.to_offset_info(ts);
let at = Printed {
dt: info.offset().to_datetime(ts),
offset: info.offset(),
zone,
abbreviation: info.abbreviation(),
};
for tok in &self.print {
match *tok {
Tok::Lit(c) => out.push(c),
Tok::Letter(c, n) => at.letter(c, n, out),
}
}
}
pub(super) fn parse(&self, input: &[u8], d: &TimeDefaults) -> Result<Stamp, TimeError> {
let start = Path::default();
self.split.as_ref().map_or_else(
|| self.walk(input, d, 0, start, self.base),
|split| self.walk_split(split, input, d, 0, [Some(start); 2], self.base),
)
}
fn walk<'i>(
&self,
input: &'i [u8],
d: &TimeDefaults,
mut i: usize,
mut path: Path<'i>,
seen: Facts,
) -> Result<Stamp, TimeError> {
while let Some(op) = self.ops.get(i) {
match op {
Op::Section { end, facts } => {
if let Ok(ts) = self.walk(input, d, i + 1, path, seen.with(*facts)) {
return Ok(ts);
}
i = *end;
}
Op::Step(step) => {
path.read(*step, input)?;
i += 1;
}
}
}
path.finish(input, d, seen)
}
fn walk_split<'i>(
&self,
split: &Split,
input: &'i [u8],
d: &TimeDefaults,
mut i: usize,
mut paths: [Option<Path<'i>>; 2],
seen: Facts,
) -> Result<Stamp, TimeError> {
while let Some(op) = self.ops.get(i) {
match op {
Op::Section { end, facts } => {
let inner = seen.with(*facts);
let mut taken = paths;
if inner.has(split.letter) {
taken[1] = None;
}
if taken.iter().any(Option::is_some)
&& let Ok(ts) = self.walk_split(split, input, d, i + 1, taken, inner)
{
return Ok(ts);
}
i = *end;
}
Op::Step(step) => {
let mut failed = None;
let other = split.without.get(i).copied().unwrap_or(Step::Never);
for (slot, step) in paths.iter_mut().zip([*step, other]) {
if let Some(path) = slot
&& let Err(e) = path.read(step, input)
{
failed = Some(e);
*slot = None;
}
}
if paths.iter().all(Option::is_none) {
return Err(failed.map_or_else(miss, TimeError::from));
}
i += 1;
}
}
}
paths[usize::from(!seen.has(split.letter))]
.ok_or_else(miss)?
.finish(input, d, seen)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op {
Section {
end: usize,
facts: Facts,
},
Step(Step),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Step {
Space,
Byte(u8),
Text(char),
Era,
Year,
Year2,
Month,
MonthAbbrev,
MonthName,
Day,
DayOfYear,
WeekdayAbbrev,
WeekdayName,
AmPm,
Hour,
Hour12,
Minute,
Second,
Fraction(Option<usize>),
Zone(ZoneText),
Skip {
min: usize,
max: usize,
},
Nanos,
Never,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ZoneText {
Offset(Zulu),
Name,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Zulu {
Accepted,
Refused,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct Facts(u16);
impl Facts {
const NONE: Self = Self(0);
const YEAR: Self = Self(1);
const WIDE_YEAR: Self = Self(1 << 1);
const WEEK_YEAR: Self = Self(1 << 2);
const MERIDIEM: Self = Self(1 << 3);
const HOUR: Self = Self(1 << 4);
const TWELVE: Self = Self(1 << 5);
const MINUTE: Self = Self(1 << 6);
const SECOND: Self = Self(1 << 7);
const FRACTION: Self = Self(1 << 8);
const fn of(tok: Tok) -> Self {
let Tok::Letter(c, n) = tok else {
return Self::NONE;
};
match c {
'y' | 'u' if n >= 4 => Self::YEAR.with(Self::WIDE_YEAR),
'y' | 'u' => Self::YEAR,
'Y' => Self::WEEK_YEAR,
'a' => Self::MERIDIEM,
'H' | 'k' => Self::HOUR,
'h' => Self::HOUR.with(Self::TWELVE),
'm' => Self::MINUTE,
's' => Self::SECOND,
'S' | 'n' | 'N' => Self::FRACTION,
_ => Self::NONE,
}
}
const fn has(self, bit: Self) -> bool {
self.0 & bit.0 != 0
}
const fn with(self, other: Self) -> Self {
Self(self.0 | other.0)
}
const fn year(self) -> Year {
if self.has(Self::WEEK_YEAR) {
Year::WeekBased
} else if self.has(Self::WIDE_YEAR) {
Year::Wide
} else if self.has(Self::YEAR) {
Year::Plain
} else {
Year::Absent
}
}
const fn clock(self) -> Clock {
let timed = self.has(Self::SECOND) || self.has(Self::FRACTION);
let gap =
self.has(Self::HOUR) && timed && !(self.has(Self::MINUTE) && self.has(Self::SECOND));
if gap || (self.has(Self::TWELVE) && !self.has(Self::MERIDIEM)) {
Clock::Dropped
} else {
Clock::Kept
}
}
}
fn facts(toks: impl Iterator<Item = Tok>) -> Facts {
toks.fold(Facts::NONE, |seen, tok| seen.with(Facts::of(tok)))
}
#[derive(Debug, Clone, Copy, Default)]
struct Ctx {
week: bool,
meridiem: bool,
exact: bool,
}
#[derive(Debug, Clone, Copy, Default)]
struct Path<'i> {
at: usize,
fields: Fields,
zone: Option<TextZone<'i>>,
}
#[derive(Debug, Clone, Copy, Default)]
struct Fields {
year: Option<i16>,
month: Option<i8>,
day: Option<i8>,
day_of_year: Option<i16>,
meridiem: Option<Meridiem>,
hour: Option<i8>,
minute: Option<i8>,
second: Option<i8>,
nanos: Option<i32>,
}
impl Fields {
fn set_hour(&mut self, hour: i8) {
self.hour = Some(self.meridiem.map_or(hour, |m| noon_side(m, hour)));
}
fn set_meridiem(&mut self, m: Meridiem) {
self.hour = self.hour.map(|hour| noon_side(m, hour));
self.meridiem = Some(m);
}
fn broken_down(&self) -> Result<BrokenDownTime, jiff::Error> {
let mut tm = BrokenDownTime::default();
tm.set_year(self.year)?;
tm.set_month(self.month)?;
tm.set_day(self.day)?;
tm.set_day_of_year(self.day_of_year)?;
tm.set_meridiem(self.meridiem);
tm.set_hour(self.hour)?;
tm.set_minute(self.minute)?;
tm.set_second(self.second)?;
tm.set_subsec_nanosecond(self.nanos)?;
Ok(tm)
}
}
const fn noon_side(m: Meridiem, hour: i8) -> i8 {
match m {
Meridiem::AM => hour % 12,
Meridiem::PM => hour % 12 + 12,
}
}
impl<'i> Path<'i> {
fn finish(self, input: &[u8], d: &TimeDefaults, seen: Facts) -> Result<Stamp, TimeError> {
if self.at != input.len() {
return Err(miss());
}
let mut tm = self.fields.broken_down()?;
let dt = civil(&mut tm, input, d, seen.year(), seen.clock())?;
place(dt, self.zone, d)
}
fn read(&mut self, step: Step, input: &'i [u8]) -> Result<(), Miss> {
let rest = input.get(self.at..).unwrap_or_default();
let f = &mut self.fields;
let used = match step {
Step::Space => rest.iter().take_while(|b| b.is_ascii_whitespace()).count(),
Step::Byte(b) if rest.first() == Some(&b) => 1,
Step::Text(c) => {
let mut buf = [0; 4];
let text = c.encode_utf8(&mut buf).as_bytes();
if !rest.starts_with(text) {
return Err(Miss::Shape);
}
text.len()
}
Step::Era if rest.starts_with(b"AD") => 2,
Step::Year => {
let sign = usize::from(matches!(rest.first(), Some(b'+' | b'-')));
let (n, used) = number(&rest[sign..], 4)?;
let year: i16 = Unit::Year.bound(n, 0, 9999)?;
f.year = Some(if rest.first() == Some(&b'-') {
-year
} else {
year
});
sign + used
}
Step::Year2 => {
let (n, used) = number(rest, 2)?;
f.year = Some(Unit::Year.bound(
if n <= 68 { n + 2000 } else { n + 1900 },
1969,
2068,
)?);
used
}
Step::Month => {
let (n, used) = number(rest, 2)?;
f.month = Some(Unit::Month.bound(n, 1, 12)?);
used
}
Step::MonthAbbrev => {
f.month = Some(abbreviation(rest, &MONTHS).ok_or(Miss::Shape)?);
3
}
Step::MonthName => {
let (i, used) = full_name(rest, &MONTHS).ok_or(Miss::Shape)?;
f.month = Some(i);
used
}
Step::Day => {
let (n, used) = number(rest, 2)?;
f.day = Some(Unit::Day.bound(n, 1, 31)?);
used
}
Step::DayOfYear => {
let (n, used) = number(rest, 3)?;
f.day_of_year = Some(Unit::DayOfYear.bound(n, 1, 366)?);
used
}
Step::WeekdayAbbrev => {
abbreviation(rest, &WEEKDAYS).ok_or(Miss::Shape)?;
3
}
Step::WeekdayName => full_name(rest, &WEEKDAYS).ok_or(Miss::Shape)?.1,
Step::AmPm => {
let half = rest.get(..2).ok_or(Miss::Shape)?;
f.set_meridiem(if half.eq_ignore_ascii_case(b"am") {
Meridiem::AM
} else if half.eq_ignore_ascii_case(b"pm") {
Meridiem::PM
} else {
return Err(Miss::Shape);
});
2
}
Step::Hour => {
let (n, used) = number(rest, 2)?;
f.set_hour(Unit::Hour.bound(n, 0, 23)?);
used
}
Step::Hour12 => {
let (n, used) = number(rest, 2)?;
f.set_hour(Unit::Hour.bound(n, 1, 12)?);
used
}
Step::Minute => {
let (n, used) = number(rest, 2)?;
f.minute = Some(Unit::Minute.bound(n, 0, 59)?);
used
}
Step::Second => {
let (n, used) = number(rest, 2)?;
f.second = Some(Unit::Second.bound(if n == 60 { 59 } else { n }, 0, 59)?);
used
}
Step::Fraction(exact) => {
let n = exact.unwrap_or_else(|| run(rest, 0).min(9));
if n == 0 || run(rest, 0) < n {
return Err(Miss::Shape);
}
f.nanos = Some(nanos(&rest[..n]));
n
}
Step::Zone(kind) => {
let (zone, used) = text_zone(rest, kind).ok_or(Miss::Zone)?;
self.zone = Some(zone);
used
}
Step::Skip { min, max } => {
let n = run(rest, 0).min(max);
if n < min {
return Err(Miss::Shape);
}
n
}
Step::Nanos => {
let n = run(rest, 0).min(9);
if n == 0 {
return Err(Miss::Shape);
}
f.nanos = Some(i32::try_from(num(&rest[..n])).map_err(|_| Miss::Shape)?);
n
}
Step::Byte(_) | Step::Era | Step::Never => return Err(Miss::Shape),
};
self.at += used;
Ok(())
}
}
const fn miss() -> TimeError {
TimeError::Shape("Java pattern")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Miss {
Shape,
Zone,
Range(Unit, i16),
}
impl From<Miss> for TimeError {
fn from(miss: Miss) -> Self {
match miss {
Miss::Shape => Self::Shape("Java pattern"),
Miss::Zone => Self::Shape("zone"),
Miss::Range(unit, n) => Self::Range(jiff::Error::from_args(format_args!(
"{} {n} is out of range",
unit.name()
))),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Unit {
Year,
Month,
Day,
DayOfYear,
Hour,
Minute,
Second,
}
impl Unit {
const fn name(self) -> &'static str {
match self {
Self::Year => "year",
Self::Month => "month",
Self::Day => "day",
Self::DayOfYear => "day of the year",
Self::Hour => "hour",
Self::Minute => "minute",
Self::Second => "second",
}
}
fn bound<T: TryFrom<i64>>(self, n: i64, lo: i64, hi: i64) -> Result<T, Miss> {
(lo..=hi)
.contains(&n)
.then(|| T::try_from(n).ok())
.flatten()
.ok_or_else(|| Miss::Range(self, i16::try_from(n).unwrap_or(i16::MAX)))
}
}
fn number(rest: &[u8], width: usize) -> Result<(i64, usize), Miss> {
let lead = rest.iter().take_while(|b| b.is_ascii_whitespace()).count();
let mut n = 0;
let mut end = lead;
while let Some(&b) = rest.get(end)
&& b.is_ascii_digit()
&& end - lead < width
{
n = n * 10 + i64::from(b - b'0');
end += 1;
}
if end == lead {
return Err(Miss::Shape);
}
Ok((n, end))
}
fn abbreviation(rest: &[u8], names: &[&str]) -> Option<i8> {
let head = rest.get(..3)?;
let i = names
.iter()
.position(|name| head.eq_ignore_ascii_case(&name.as_bytes()[..3]))?;
i8::try_from(i + 1).ok()
}
fn full_name(rest: &[u8], names: &[&str]) -> Option<(i8, usize)> {
names.iter().zip(1..).find_map(|(name, i)| {
rest.get(..name.len())
.filter(|head| head.eq_ignore_ascii_case(name.as_bytes()))
.map(|_| (i, name.len()))
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Year {
Plain,
Wide,
WeekBased,
Absent,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Clock {
Kept,
Dropped,
}
fn civil(
tm: &mut BrokenDownTime,
input: &[u8],
d: &TimeDefaults,
year: Year,
clock: Clock,
) -> Result<DateTime, TimeError> {
tm.set_weekday(None);
let date = match year {
Year::WeekBased => {
let first = Date::new(tm.year().ok_or(TimeError::Shape("Java pattern"))?, 1, 1)?;
let back = i64::from(first.weekday().to_sunday_zero_offset());
first.checked_sub(jiff::Span::new().try_days(back)?)?
}
Year::Wide => {
let year = tm.year().ok_or(TimeError::Shape("Java pattern"))?;
if (0..1000).contains(&year) && !four_digits_in(input, year) {
return Err(TimeError::Shape("4-digit year"));
}
first_of_year(tm)?;
tm.to_date()?
}
Year::Plain => {
first_of_year(tm)?;
tm.to_date()?
}
Year::Absent => {
if let Some(month) = tm.month() {
tm.set_year(Some(year_for(d, month, tm.day().unwrap_or(1))?))?;
} else {
tm.set_year(Some(this_year(d)?))?;
first_of_year(tm)?;
}
tm.to_date()?
}
};
let time = match clock {
Clock::Kept => tm.to_time()?,
Clock::Dropped => Time::midnight(),
};
Ok(DateTime::from_parts(date, time))
}
fn first_of_year(tm: &mut BrokenDownTime) -> Result<(), jiff::Error> {
if tm.month().is_none() && tm.day_of_year().is_none() {
tm.set_month(Some(1))?;
if tm.day().is_none() {
tm.set_day(Some(1))?;
}
}
Ok(())
}
fn this_year(d: &TimeDefaults) -> Result<i16, TimeError> {
match (d.year, d.now) {
(Some(year), _) => Ok(year),
(None, Some(now)) => Ok(d.zone.to_datetime(now).year()),
(None, None) => Err(TimeError::NoYear),
}
}
fn four_digits_in(input: &[u8], year: i16) -> bool {
let mut digits = [b'0'; 4];
let mut y = year.unsigned_abs();
for slot in digits.iter_mut().rev() {
*slot = b'0' + u8::try_from(y % 10).unwrap_or(0);
y /= 10;
}
input.windows(4).any(|w| w == digits)
}
#[derive(Debug, Clone, Copy)]
enum TextZone<'a> {
Fixed(Offset),
Named(&'a str),
}
fn place(dt: DateTime, zone: Option<TextZone<'_>>, d: &TimeDefaults) -> Result<Stamp, TimeError> {
Ok(match zone {
Some(TextZone::Fixed(off)) => Stamp::zoned(off.to_timestamp(dt)?, off),
Some(TextZone::Named(name)) => {
let tz = TimeZone::get(name)?;
let ts = tz.to_timestamp(dt)?;
Stamp::zoned(ts, tz.to_offset(ts))
}
None => Stamp::zone_less(d.zone.to_timestamp(dt)?),
})
}
fn text_zone(rest: &[u8], kind: ZoneText) -> Option<(TextZone<'_>, usize)> {
let text = std::str::from_utf8(rest).ok()?;
let trimmed = text.trim_start();
let lead = text.len() - trimmed.len();
let b = trimmed.as_bytes();
if matches!(b.first(), Some(b'+' | b'-')) {
let (off, used) = numeric_offset(b)?;
return Some((TextZone::Fixed(off), lead + used));
}
match kind {
ZoneText::Offset(Zulu::Accepted) if b.first() == Some(&b'Z') => {
return Some((TextZone::Fixed(Offset::UTC), lead + 1));
}
ZoneText::Offset(_) => return None,
ZoneText::Name => {}
}
let len = zone_id_len(b);
let name = trimmed.get(..len).filter(|n| !n.is_empty())?;
if matches!(name, "UTC" | "GMT" | "UT") && matches!(b.get(len), Some(b'+' | b'-')) {
let (off, used) = numeric_offset(&b[len..])?;
return Some((TextZone::Fixed(off), lead + len + used));
}
Some((named_zone(name)?, lead + len))
}
fn zone_id_len(b: &[u8]) -> usize {
if !b.first().is_some_and(u8::is_ascii_alphabetic) {
return 0;
}
let mut region = false;
b.iter()
.take_while(|&&c| {
region |= c == b'/';
c.is_ascii_alphabetic()
|| matches!(c, b'_' | b'/')
|| (region && (c.is_ascii_digit() || matches!(c, b'-' | b'+')))
})
.count()
}
fn numeric_offset(b: &[u8]) -> Option<(Offset, usize)> {
let neg = *b.first()? == b'-';
let two = |at: usize| (run(b, at) >= 2).then(|| num(&b[at..at + 2]));
let mut secs = two(1)? * 3600;
let mut end = 3;
for unit in [60, 1] {
let at = if b.get(end) == Some(&b':') {
end + 1
} else {
end
};
let Some(v) = two(at) else { break };
secs += v * unit;
end = at + 2;
}
if secs > 18 * 3600 {
return None;
}
let secs = i32::try_from(if neg { -secs } else { secs }).ok()?;
Some((Offset::from_seconds(secs).ok()?, end))
}
fn named_zone(name: &str) -> Option<TextZone<'_>> {
if matches!(name, "UTC" | "GMT" | "UT" | "Z" | "Zulu") {
return Some(TextZone::Fixed(Offset::UTC));
}
if let Some(&(_, minutes)) = FIXED_ZONES.iter().find(|(n, _)| *n == name) {
return Offset::from_seconds(minutes * 60).ok().map(TextZone::Fixed);
}
if let Some(&(_, zone)) = SHARED_ZONES.iter().find(|(n, _)| *n == name) {
return Some(TextZone::Named(zone));
}
name.contains('/').then_some(TextZone::Named(name))
}
struct Printed<'z> {
dt: DateTime,
offset: Offset,
zone: &'z TimeZone,
abbreviation: &'z str,
}
impl Printed<'_> {
fn letter(&self, c: char, n: usize, out: &mut String) {
let (date, time) = (self.dt.date(), self.dt.time());
match (c, n) {
('G', _) => out.push_str(if date.year() > 0 { "AD" } else { "BC" }),
('u', _) => year(out, i64::from(date.year()), n),
('y', _) => year(out, i64::from(year_of_era(date.year())), n),
('Y', _) => year(out, i64::from(week_year(date)), n),
('M' | 'L', 3) => out.push_str(&MONTHS[month_index(date)][..3]),
('M' | 'L', 4) => out.push_str(MONTHS[month_index(date)]),
('M' | 'L', _) => pad(out, date.month().into(), n),
('d', _) => pad(out, date.day().into(), n),
('D', _) => pad(out, date.day_of_year().into(), n),
('E', 4) => out.push_str(WEEKDAYS[weekday_index(date)]),
('E', _) => out.push_str(&WEEKDAYS[weekday_index(date)][..3]),
('w', _) => pad(out, week_of_week_year(date), n),
('W', _) => {
let lead = i64::from(date.first_of_month().weekday().to_sunday_zero_offset());
pad(out, (i64::from(date.day()) - 1 + lead) / 7 + 1, n);
}
('F', _) => pad(out, (i64::from(date.day()) - 1) / 7 + 1, n),
('a', _) => out.push_str(if time.hour() < 12 { "AM" } else { "PM" }),
('H', _) => pad(out, time.hour().into(), n),
('k', _) => pad(
out,
if time.hour() == 0 {
24
} else {
time.hour().into()
},
n,
),
('h', _) => pad(out, (i64::from(time.hour()) + 11) % 12 + 1, n),
('m', _) => pad(out, time.minute().into(), n),
('s', _) => pad(out, time.second().into(), n),
('S', _) => {
let mut digits = [0; 9];
fill(&mut digits, i64::from(time.subsec_nanosecond()));
for &d in digits.iter().take(n.min(9)) {
out.push(char::from(b'0' + d));
}
}
('n', _) => pad(out, time.subsec_nanosecond().into(), n),
('N', _) => {
let secs = (i64::from(time.hour()) * 60 + i64::from(time.minute())) * 60
+ i64::from(time.second());
pad(
out,
secs * 1_000_000_000 + i64::from(time.subsec_nanosecond()),
n,
);
}
('X', _) => offset_text(out, self.offset, n, Some("Z")),
('x', _) => offset_text(out, self.offset, n, None),
('Z', 1..=3) => offset_text(out, self.offset, 2, None),
('Z', 4) => {
out.push_str("GMT");
if self.offset != Offset::UTC {
offset_text(out, self.offset, 5, None);
}
}
('Z', _) => offset_text(out, self.offset, 5, Some("Z")),
('V', _) => match self.zone.iana_name() {
Some(name) => out.push_str(name),
None => offset_text(out, self.offset, 5, Some("Z")),
},
_ if self.zone.iana_name().is_some() || *self.zone == TimeZone::UTC => {
out.push_str(self.abbreviation);
}
_ => offset_text(out, self.offset, 5, Some("Z")),
}
}
}
fn month_index(date: Date) -> usize {
date.month().unsigned_abs() as usize - 1
}
fn weekday_index(date: Date) -> usize {
date.weekday().to_sunday_zero_offset().unsigned_abs() as usize
}
const fn year_of_era(year: i16) -> i16 {
if year > 0 { year } else { 1 - year }
}
fn week_start(year: i16) -> Option<Date> {
let first = Date::new(year, 1, 1).ok()?;
let back = first.weekday().to_sunday_zero_offset();
first.checked_sub(jiff::Span::new().days(back)).ok()
}
fn week_year(date: Date) -> i16 {
let next = date.year().saturating_add(1);
match week_start(next) {
Some(start) if date >= start => next,
_ => date.year(),
}
}
fn week_of_week_year(date: Date) -> i64 {
week_start(week_year(date))
.and_then(|start| start.until(date).ok())
.map_or(1, |span| i64::from(span.get_days()) / 7 + 1)
}
fn year(out: &mut String, year: i64, n: usize) {
if n == 2 {
pad(out, year.rem_euclid(100), 2);
} else {
pad(out, year, n);
}
}
fn pad(out: &mut String, value: i64, width: usize) {
if value < 0 {
out.push('-');
}
let mut digits = [0_u8; 20];
let mut v = value.unsigned_abs();
let mut len = 0;
while v > 0 || len == 0 {
digits[len] = u8::try_from(v % 10).unwrap_or(0);
v /= 10;
len += 1;
}
for _ in len..width {
out.push('0');
}
for &d in digits[..len].iter().rev() {
out.push(char::from(b'0' + d));
}
}
fn fill(digits: &mut [u8; 9], nanos: i64) {
let mut v = nanos.unsigned_abs();
for slot in digits.iter_mut().rev() {
*slot = u8::try_from(v % 10).unwrap_or(0);
v /= 10;
}
}
fn offset_text(out: &mut String, offset: Offset, width: usize, zero: Option<&str>) {
if let (Some(text), true) = (zero, offset == Offset::UTC) {
out.push_str(text);
return;
}
let secs = offset.seconds();
out.push(if secs < 0 { '-' } else { '+' });
let abs = i64::from(secs.unsigned_abs());
let (h, m, s) = (abs / 3600, abs / 60 % 60, abs % 60);
let colon = matches!(width, 3 | 5);
pad(out, h, 2);
if width == 1 && m == 0 {
return;
}
if colon {
out.push(':');
}
pad(out, m, 2);
if width >= 4 && s != 0 {
if colon {
out.push(':');
}
pad(out, s, 2);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Tok {
Lit(char),
Letter(char, usize),
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Node {
Tok(Tok),
Optional(Vec<Self>),
}
fn tree(pattern: &str) -> Result<Vec<Node>, &'static str> {
let mut stack: Vec<Vec<Node>> = vec![Vec::new()];
let mut chars = pattern.chars().peekable();
while let Some(c) = chars.next() {
let mut tok = |t: Tok| {
if let Some(top) = stack.last_mut() {
top.push(Node::Tok(t));
}
};
match c {
'\'' if chars.next_if_eq(&'\'').is_some() => tok(Tok::Lit('\'')),
'\'' => loop {
match chars.next() {
None => return Err("an unclosed quote"),
Some('\'') if chars.next_if_eq(&'\'').is_some() => tok(Tok::Lit('\'')),
Some('\'') => break,
Some(quoted) => tok(Tok::Lit(quoted)),
}
},
'[' => stack.push(Vec::new()),
']' => {
let body = stack
.pop()
.filter(|_| !stack.is_empty())
.ok_or("a ] with no [")?;
if let Some(top) = stack.last_mut() {
top.push(Node::Optional(body));
}
}
c if c.is_ascii_alphabetic() => {
let mut n = 1;
while chars.next_if_eq(&c).is_some() {
n += 1;
}
tok(Tok::Letter(c, n));
}
other => tok(Tok::Lit(other)),
}
}
while stack.len() > 1 {
if let Some(body) = stack.pop()
&& let Some(top) = stack.last_mut()
{
top.push(Node::Optional(body));
}
}
Ok(stack.pop().unwrap_or_default())
}
fn readings(nodes: &[Node]) -> Option<usize> {
nodes.iter().try_fold(1_usize, |n, node| match node {
Node::Tok(_) => Some(n),
Node::Optional(body) => n
.checked_mul(readings(body)? + 1)
.filter(|&total| total <= MAX_READINGS),
})
}
fn tokens(nodes: &[Node], left_out: Option<char>, out: &mut Vec<Tok>) {
for node in nodes {
match node {
Node::Tok(tok) => out.push(*tok),
Node::Optional(body) => {
let holds = |c: char| {
body.iter()
.any(|n| matches!(n, Node::Tok(Tok::Letter(l, _)) if *l == c))
};
if !left_out.is_some_and(holds) {
tokens(body, left_out, out);
}
}
}
}
}
fn check(toks: &[Tok]) -> Result<(), String> {
let seen = facts(toks.iter().copied());
let week = seen.has(Facts::WEEK_YEAR);
if week && seen.has(Facts::YEAR) {
return Err("letter Y beside y or u".to_owned());
}
let week_only = |c: char| "YMLdDwWFHkmsS".contains(c);
if week
&& let Some(Tok::Letter(c, n)) = toks
.iter()
.find(|t| matches!(t, Tok::Letter(c, _) if !week_only(*c)))
{
return Err(format!("letter {} beside Y", c.to_string().repeat(*n)));
}
let ctx = Ctx {
week,
meridiem: seen.has(Facts::MERIDIEM),
exact: false,
};
for tok in toks {
lower(*tok, ctx)?;
}
Ok(())
}
fn compile(nodes: &[Node], ctx: [Ctx; 2], ops: &mut Vec<Op>, without: &mut Vec<Step>) {
for node in nodes {
match node {
Node::Tok(tok) => {
let [first, second] = ctx.map(|c| lower(*tok, c).unwrap_or(Step::Never));
ops.push(Op::Step(first));
without.push(second);
}
Node::Optional(body) => {
let at = ops.len();
ops.push(Op::Section {
end: at,
facts: direct(body),
});
without.push(Step::Never);
compile(body, ctx, ops, without);
let len = ops.len();
if len == at + 1 {
ops.truncate(at);
without.truncate(at);
} else if let Some(Op::Section { end, .. }) = ops.get_mut(at) {
*end = len;
}
}
}
}
}
fn direct(nodes: &[Node]) -> Facts {
facts(nodes.iter().filter_map(|node| match node {
Node::Tok(tok) => Some(*tok),
Node::Optional(_) => None,
}))
}
fn lower(tok: Tok, ctx: Ctx) -> Result<Step, String> {
let (c, n) = match tok {
Tok::Lit(c) if c.is_ascii_whitespace() => return Ok(Step::Space),
Tok::Lit(c) => {
return Ok(match u8::try_from(c) {
Ok(b) if b.is_ascii() => Step::Byte(b),
_ => Step::Text(c),
});
}
Tok::Letter(c, n) => (c, n),
};
Ok(match (c, n) {
('M' | 'L' | 'd' | 'D' | 'w' | 'W' | 'F', _) if ctx.week => {
if n == 1 {
Step::Skip { min: 1, max: 10 }
} else {
Step::Skip { min: n, max: n }
}
}
('n' | 'N', _) => Step::Nanos,
('z' | 'v' | 'V', _) | ('Z', 4) => Step::Zone(ZoneText::Name),
('X', 1..=5) | ('Z', 5) => Step::Zone(ZoneText::Offset(Zulu::Accepted)),
('x', 1..=5) | ('Z', 1..=3) => Step::Zone(ZoneText::Offset(Zulu::Refused)),
('G', 1..=3) => Step::Era,
('y' | 'u' | 'Y', 2) => Step::Year2,
('y' | 'u' | 'Y', _) => Step::Year,
('M' | 'L', 1 | 2) => Step::Month,
('M' | 'L', 3) => Step::MonthAbbrev,
('M' | 'L', 4) => Step::MonthName,
('d', 1 | 2) => Step::Day,
('D', 1..=3) => Step::DayOfYear,
('E', 1..=3) => Step::WeekdayAbbrev,
('E', 4) => Step::WeekdayName,
('a', 1) => Step::AmPm,
('h', 1 | 2) if ctx.meridiem => Step::Hour12,
('H' | 'k' | 'h', 1 | 2) => Step::Hour,
('m', 1 | 2) => Step::Minute,
('s', 1 | 2) => Step::Second,
('S', 1..=9) => Step::Fraction(ctx.exact.then_some(n)),
_ => return Err(format!("letter {}", c.to_string().repeat(n))),
})
}