#![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 dialect;
mod java;
mod render;
pub use cache::FormatCache;
pub use dialect::StrptimeDialect;
pub use java::JavaPattern;
pub use render::{Fraction, RenderFormat, render, render_into};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TimeFormat {
Iso8601,
Iso8601Strict,
HttpDate,
Syslog,
Epoch(EpochUnit),
Rfc2822,
Strptime(String),
Java(JavaPattern),
Tai64n,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EpochUnit {
Seconds,
Millis,
Micros,
Nanos,
Auto,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeDefaults {
pub zone: TimeZone,
pub year: Option<i16>,
pub now: Option<Timestamp>,
pub year_rule: YearRule,
}
impl Default for TimeDefaults {
fn default() -> Self {
Self {
zone: TimeZone::UTC,
year: None,
now: None,
year_rule: YearRule::Nearest,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum YearRule {
#[default]
Nearest,
ThisYear,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Stamp {
pub timestamp: Timestamp,
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,
}
}
#[must_use]
pub fn zone_or(&self, zone: &TimeZone) -> TimeZone {
self.offset.map_or_else(|| zone.clone(), TimeZone::fixed)
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum TimeError {
#[error("not a {0} timestamp")]
Shape(&'static str),
#[error("a timestamp with no year needs one in the defaults")]
NoYear,
#[error("strptime directive {0} can't be parsed")]
Directive(String),
#[error("Java-style date pattern {pattern:?} has {part}")]
Pattern {
pattern: String,
part: String,
},
#[error(transparent)]
Range(#[from] jiff::Error),
}
pub fn parse_time(
format: &TimeFormat,
input: &[u8],
defaults: &TimeDefaults,
) -> Result<Timestamp, TimeError> {
parse_stamp(format, input, defaults).map(|stamp| stamp.timestamp)
}
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(unit) => Ok(Stamp::zoned(epoch(input, *unit)?, Offset::UTC)),
TimeFormat::Tai64n => Ok(Stamp::zoned(tai64n(input)?, Offset::UTC)),
TimeFormat::Java(pattern) => pattern.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() {
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))
}
}
}
}
pub fn parse_time_any(
formats: &[TimeFormat],
input: &[u8],
defaults: &TimeDefaults,
) -> Result<Timestamp, TimeError> {
parse_stamp_any(formats, input, defaults).map(|stamp| stamp.timestamp)
}
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)
}
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)),
}
}
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())
}
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"))
}
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,
)?)
}
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 })?)
}
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))
}
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))
}
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)?))
}
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()),
}
}
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)
}
}
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 whole <= 1_000_000_000_000_000_000 => 3,
EpochUnit::Nanos | EpochUnit::Auto => 0,
};
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 })?)
}
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'));
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::Micros | EpochUnit::Auto => 1_000_000,
EpochUnit::Nanos => 1_000_000_000,
};
let unit_ns = 1_000_000_000 / per_second;
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)?)
}
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;