use std::collections::BTreeMap;
use crate::{Error, Result, Value};
use super::clock::ClockKind;
use super::Temporal;
pub(super) type Fields = BTreeMap<String, Value>;
pub(super) const DAY_OF_WEEK_KEYS: &[&str] = &["dayOfWeek", "dayofweek"];
pub(super) const ORDINAL_DAY_KEYS: &[&str] = &["ordinalDay", "ordinalday"];
pub(super) const DAY_OF_QUARTER_KEYS: &[&str] = &["dayOfQuarter", "dayofquarter"];
pub(super) const EPOCH_MILLIS_KEYS: &[&str] = &["epochMillis", "epochmillis"];
pub(super) const EPOCH_SECONDS_KEYS: &[&str] = &["epochSeconds", "epochseconds"];
fn present_value<'a>(m: &'a Fields, key: &str) -> Option<&'a Value> {
m.get(key).filter(|value| !value.is_null())
}
pub(super) fn present(m: &Fields, key: &str) -> bool {
present_value(m, key).is_some()
}
pub(super) fn present_alias(m: &Fields, keys: &[&str]) -> bool {
keys.iter().any(|key| present(m, key))
}
fn is_date_field(key: &str) -> bool {
key == "year"
|| DATE_FORM_RULES
.iter()
.any(|rule| rule.primary_keys.contains(&key) || rule.day_keys.contains(&key))
}
fn is_time_field(key: &str) -> bool {
matches!(
key,
"hour" | "minute" | "second" | "millisecond" | "microsecond" | "nanosecond"
)
}
pub(super) fn is_epoch_field(key: &str) -> bool {
EPOCH_MILLIS_KEYS.contains(&key) || EPOCH_SECONDS_KEYS.contains(&key)
}
fn accepts(kind: ClockKind, key: &str) -> bool {
match key {
"timezone" => true,
"date" => kind.has_date(),
"time" => kind.has_time(),
"datetime" => kind.has_date_and_time(),
_ => {
is_date_field(key) && kind.has_date()
|| is_time_field(key) && kind.has_time()
|| is_epoch_field(key) && kind.has_epoch()
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum DateForm {
Calendar,
Week,
Ordinal,
Quarter,
}
struct DateFormRule {
form: DateForm,
primary_keys: &'static [&'static str],
day_keys: &'static [&'static str],
time_needs_both: bool,
}
const DATE_FORM_RULES: &[DateFormRule] = &[
DateFormRule {
form: DateForm::Calendar,
primary_keys: &["month"],
day_keys: &["day"],
time_needs_both: true,
},
DateFormRule {
form: DateForm::Week,
primary_keys: &["week"],
day_keys: DAY_OF_WEEK_KEYS,
time_needs_both: true,
},
DateFormRule {
form: DateForm::Ordinal,
primary_keys: ORDINAL_DAY_KEYS,
day_keys: &[],
time_needs_both: false,
},
DateFormRule {
form: DateForm::Quarter,
primary_keys: &["quarter"],
day_keys: DAY_OF_QUARTER_KEYS,
time_needs_both: true,
},
];
impl DateFormRule {
fn selects(&self, m: &Fields) -> bool {
present_alias(m, self.primary_keys) || present_alias(m, self.day_keys)
}
fn primary_name(&self) -> &'static str {
self.primary_keys
.first()
.copied()
.expect("every date form names a primary field")
}
fn day_name(&self) -> Option<&'static str> {
self.day_keys.first().copied()
}
}
fn date_form(m: &Fields) -> Result<Option<&'static DateFormRule>> {
let mut selected = DATE_FORM_RULES.iter().filter(|rule| rule.selects(m));
let first = selected.next();
if selected.next().is_some() {
return Err(Error::ty(
"Cannot combine calendar, week, ordinal and quarter date fields.",
));
}
Ok(first)
}
fn required(field: &str) -> Error {
Error::ty(format!("{field} must be specified"))
}
fn required_year() -> Error {
Error::argument_error("year must be specified")
}
pub(super) fn at_least_one_unit() -> Error {
Error::argument_error("At least one temporal unit must be specified.")
}
fn cannot_get(part: &str, value: &Value) -> Error {
match value {
Value::Temporal(t) => cannot_get_temporal(part, t),
other => Error::ty(format!(
"Cannot get the {part} of: {}",
other.to_display_string()
)),
}
}
pub(super) fn cannot_get_temporal(part: &str, t: &Temporal) -> Error {
Error::ty(format!("Cannot get the {part} of: {}", t.iso_string()))
}
pub(super) struct Sources<'a> {
pub(super) date: Option<&'a Temporal>,
pub(super) time: Option<&'a Temporal>,
}
impl Sources<'_> {
fn has_date(&self) -> bool {
self.date.is_some()
}
fn has_time(&self) -> bool {
self.time.is_some()
}
}
pub(super) struct Validated<'a> {
pub(super) form: Option<DateForm>,
pub(super) sources: Sources<'a>,
}
pub(super) fn validate(kind: ClockKind, m: &Fields) -> Result<Validated<'_>> {
check_vocabulary(kind, m)?;
if !m.values().any(|value| !value.is_null()) {
return Err(at_least_one_unit());
}
check_timezone(kind, m)?;
let sources = check_sources(m)?;
let form = check_date_fields(kind, m, &sources)?;
check_time_fields(m, &sources)?;
check_day_of_week(m)?;
Ok(Validated { form, sources })
}
fn check_timezone(kind: ClockKind, m: &Fields) -> Result<()> {
if !kind.has_zone()
&& present(m, "timezone")
&& m.iter()
.any(|(key, value)| key != "timezone" && !value.is_null())
{
return Err(Error::ty(
"Cannot assign time zone if also assigning other fields.",
));
}
Ok(())
}
fn check_sources(m: &Fields) -> Result<Sources<'_>> {
if present(m, "datetime") && (present(m, "date") || present(m, "time")) {
return Err(Error::argument_error(
"datetime cannot be selected together with date or time.",
));
}
let datetime = match present_value(m, "datetime") {
None => None,
Some(value) => match value.as_temporal() {
Some(t) if t.has_date_and_time() => Some(t),
Some(t) => {
let part = if t.has_date() { "time" } else { "date" };
return Err(cannot_get(part, value));
}
None => return Err(cannot_get("datetime", value)),
},
};
let date = source_field(m, "date", Temporal::has_date)?;
let time = source_field(m, "time", Temporal::has_time)?;
Ok(Sources {
date: datetime.or(date),
time: datetime.or(time),
})
}
fn source_field<'a>(
m: &'a Fields,
key: &str,
carries: fn(&Temporal) -> bool,
) -> Result<Option<&'a Temporal>> {
match present_value(m, key) {
None => Ok(None),
Some(value) => match value.as_temporal() {
Some(t) if carries(t) => Ok(Some(t)),
_ => Err(cannot_get(key, value)),
},
}
}
fn check_date_fields(
kind: ClockKind,
m: &Fields,
sources: &Sources<'_>,
) -> Result<Option<DateForm>> {
if !kind.has_date() {
return Ok(None);
}
let rule = date_form(m)?;
let time_present = is_time_field_present(m) || sources.has_time();
if sources.has_date() {
return Ok(rule.map(|rule| rule.form));
}
if rule.is_none() && !present(m, "year") && !time_present {
return Ok(None);
}
if !present(m, "year") {
return Err(required_year());
}
let rule = rule.unwrap_or(&DATE_FORM_RULES[0]);
if let Some(day) = rule.day_name() {
if present_alias(m, rule.day_keys) && !present_alias(m, rule.primary_keys) {
return Err(Error::ty(format!(
"{day} cannot be specified without {}",
rule.primary_name()
)));
}
}
if time_present && rule.time_needs_both {
if !present_alias(m, rule.primary_keys) {
return Err(required(rule.primary_name()));
}
if let Some(day) = rule.day_name() {
if !present_alias(m, rule.day_keys) {
return Err(required(day));
}
}
}
Ok(Some(rule.form))
}
fn is_time_field_present(m: &Fields) -> bool {
m.keys().any(|key| is_time_field(key) && present(m, key))
}
fn check_time_fields(m: &Fields, sources: &Sources<'_>) -> Result<()> {
if !is_time_field_present(m) || sources.has_time() {
return Ok(());
}
let subsecond =
present(m, "millisecond") || present(m, "microsecond") || present(m, "nanosecond");
if !present(m, "hour") {
return Err(required("hour"));
}
if (present(m, "second") || subsecond) && !present(m, "minute") {
return Err(required("minute"));
}
if subsecond && !present(m, "second") {
return Err(required("second"));
}
Ok(())
}
fn check_day_of_week(m: &Fields) -> Result<()> {
for key in DAY_OF_WEEK_KEYS {
if let Some(Value::Int(day)) = m.get(*key) {
if !(1..=7).contains(day) {
return Err(Error::argument_error(format!(
"Invalid value for DayOfWeek (valid values 1 - 7): {day}"
)));
}
}
}
Ok(())
}
fn check_vocabulary(kind: ClockKind, m: &Fields) -> Result<()> {
for key in m.keys() {
if !accepts(kind, key) {
return Err(Error::ty(format!("Not supported: {key}")));
}
}
Ok(())
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum EpochField {
Seconds,
Millis,
}
impl EpochField {
pub(super) fn keys(self) -> &'static [&'static str] {
match self {
EpochField::Seconds => EPOCH_SECONDS_KEYS,
EpochField::Millis => EPOCH_MILLIS_KEYS,
}
}
pub(super) fn name(self) -> &'static str {
self.keys()[0]
}
pub(super) fn split(self, value: i64) -> (i64, u32) {
match self {
EpochField::Seconds => (value, 0),
EpochField::Millis => (
value.div_euclid(1000),
u32::try_from(value.rem_euclid(1000) * 1_000_000)
.expect("a millisecond remainder is below 10^9"),
),
}
}
}
pub(super) fn validate_epoch(kind: ClockKind, m: &Fields) -> Result<EpochField> {
check_vocabulary(kind, m)?;
let seconds = present_alias(m, EPOCH_SECONDS_KEYS);
let millis = present_alias(m, EPOCH_MILLIS_KEYS);
if seconds && millis {
return Err(Error::argument_error(
"epochSeconds cannot be selected together with epochMillis.",
));
}
for key in ["date", "time", "datetime"] {
if present(m, key) {
return Err(Error::argument_error(format!(
"epoch fields cannot be selected together with {key}."
)));
}
}
match (seconds, millis) {
(true, false) => Ok(EpochField::Seconds),
(false, true) => Ok(EpochField::Millis),
_ => Err(at_least_one_unit()),
}
}