use std::borrow::Cow;
use super::{ChronoFormat, JavaPattern, TimeError, TimeFormat};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum StrptimeDialect {
Jiff,
PercentL,
Ctime,
PercentN,
Java,
JavaStrict,
Chrono,
}
impl TimeFormat {
pub fn strptime(dialect: StrptimeDialect, format: &str) -> Result<Self, TimeError> {
match dialect {
StrptimeDialect::Jiff => return Ok(Self::Strptime(format.to_owned())),
StrptimeDialect::Chrono => return ChronoFormat::build(format).map(Self::Chrono),
StrptimeDialect::Java => return JavaPattern::build(format, false).map(Self::Java),
StrptimeDialect::JavaStrict => {
return JavaPattern::build(format, true).map(Self::Java);
}
_ => {}
}
let mut out = String::with_capacity(format.len() + 8);
let mut rest = format;
while let Some(at) = rest.find('%') {
out.push_str(&rest[..at]);
let tail = &rest[at + 1..];
let len = tail
.char_indices()
.find(|&(_, c)| c.is_ascii_alphabetic() || matches!(c, '%' | '+'))
.map(|(i, c)| i + c.len_utf8())
.ok_or_else(|| TimeError::Directive(rest[at..].to_owned()))?;
out.push_str(&directive(dialect, &rest[at..=at + len])?);
rest = &tail[len..];
}
out.push_str(rest);
Ok(Self::Strptime(out))
}
}
fn directive(dialect: StrptimeDialect, spec: &str) -> Result<Cow<'_, str>, TimeError> {
let refuse = || Err(TimeError::Directive(spec.to_owned()));
let mapped = match (dialect, spec) {
(_, "%Z") | (StrptimeDialect::PercentN, "%c" | "%+" | "%x" | "%X" | "%E") => {
return refuse();
}
(StrptimeDialect::PercentL | StrptimeDialect::Ctime, "%L") => "%f",
(StrptimeDialect::Ctime, "%o") => "%_m",
(StrptimeDialect::Ctime, "%q") => "%-m",
(StrptimeDialect::Ctime, "%g") => "%-d",
(StrptimeDialect::Ctime, "%l") => "%-I",
(StrptimeDialect::Ctime, "%w") => "%z",
(StrptimeDialect::Ctime, "%i") => "%:::z",
(StrptimeDialect::Ctime, "%j") => "%:z",
(StrptimeDialect::Ctime, "%k") => "%::z",
(StrptimeDialect::Ctime, "%D" | "%x") => "%m/%d/%Y",
(StrptimeDialect::Ctime, "%T" | "%X") => "%H:%M:%S",
(StrptimeDialect::Ctime, "%r") => "%I:%M:%S %P",
(StrptimeDialect::Ctime, "%c") => "%a %b %d %H:%M:%S %Y",
(StrptimeDialect::PercentN, _) if spec.ends_with(['N', 'Q']) => {
return Ok(Cow::Owned(format!("{}f", &spec[..spec.len() - 1])));
}
_ => spec,
};
Ok(Cow::Borrowed(mapped))
}