use crate::Error;
use std::fmt::{self, Display};
use std::str::FromStr;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Date {
year: u16,
month: u8,
day: u8,
}
pub(crate) const TOKEN: &str = "$soml::Date";
impl Date {
#[must_use]
pub fn new(year: u16, month: u8, day: u8) -> Option<Self> {
Self::calendar_error(u32::from(year), u32::from(month), u32::from(day))
.is_none()
.then_some(Self { year, month, day })
}
#[must_use]
pub const fn year(self) -> u16 {
self.year
}
#[must_use]
pub const fn month(self) -> u8 {
self.month
}
#[must_use]
pub const fn day(self) -> u8 {
self.day
}
pub(crate) fn parse(text: &str) -> Result<Self, String> {
let bytes = text.as_bytes();
if bytes.len() != 10 || !crate::scalar::has_date_prefix(bytes) {
return Err(format!(
"Invalid date “{}”. A date is written as YYYY-MM-DD",
crate::abbreviate(text, 40)
));
}
let year = u32::from(bytes[0] - b'0') * 1000
+ u32::from(bytes[1] - b'0') * 100
+ u32::from(bytes[2] - b'0') * 10
+ u32::from(bytes[3] - b'0');
let month = u32::from(bytes[5] - b'0') * 10 + u32::from(bytes[6] - b'0');
let day = u32::from(bytes[8] - b'0') * 10 + u32::from(bytes[9] - b'0');
if let Some(problem) = Self::calendar_error(year, month, day) {
return Err(format!("Invalid date {text}: {problem}"));
}
Ok(Self {
year: year as u16,
month: month as u8,
day: day as u8,
})
}
pub(crate) fn calendar_error(year: u32, month: u32, day: u32) -> Option<String> {
if !(1..=9999).contains(&year) {
return Some("the year must be 0001 to 9999".to_owned());
}
if !(1..=12).contains(&month) {
return Some("the month must be 01 to 12".to_owned());
}
let last_day = Self::days_in_month(year, month);
if day < 1 || day > last_day {
return Some(format!("the day must be 01 to {last_day} in that month"));
}
None
}
const fn days_in_month(year: u32, month: u32) -> u32 {
let is_leap_year =
year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400));
match month {
2 if is_leap_year => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
}
impl Display for Date {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut text = *b"0000-00-00";
crate::instant::put_digits(&mut text[..4], u32::from(self.year));
crate::instant::put_digits(&mut text[5..7], u32::from(self.month));
crate::instant::put_digits(&mut text[8..], u32::from(self.day));
formatter.write_str(std::str::from_utf8(&text).expect("the digits are ASCII"))
}
}
impl fmt::Debug for Date {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "Date({self})")
}
}
impl FromStr for Date {
type Err = Error;
fn from_str(text: &str) -> Result<Self, Error> {
Self::parse(text).map_err(Error::syntax)
}
}
serde_temporal_scalar!(Date, "a date");