use core::fmt;
use jiff::civil;
use crate::time::error::TimeError;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Date(civil::Date);
impl Date {
pub fn new(year: i16, month: i8, day: i8) -> Result<Self, TimeError> {
civil::Date::new(year, month, day)
.map(Self)
.map_err(|_| TimeError::DateInvalid { year, month, day })
}
#[must_use]
pub fn year(&self) -> i16 {
self.0.year()
}
#[must_use]
pub fn month(&self) -> i8 {
self.0.month()
}
#[must_use]
pub fn day(&self) -> i8 {
self.0.day()
}
#[must_use]
pub fn weekday(&self) -> Weekday {
match self.0.weekday() {
civil::Weekday::Monday => Weekday::Monday,
civil::Weekday::Tuesday => Weekday::Tuesday,
civil::Weekday::Wednesday => Weekday::Wednesday,
civil::Weekday::Thursday => Weekday::Thursday,
civil::Weekday::Friday => Weekday::Friday,
civil::Weekday::Saturday => Weekday::Saturday,
civil::Weekday::Sunday => Weekday::Sunday,
}
}
pub fn plus_days(self, days: i64) -> Result<Self, TimeError> {
const SECONDS_PER_DAY: i64 = 60 * 60 * 24;
let seconds = days
.checked_mul(SECONDS_PER_DAY)
.ok_or(TimeError::DateOverflow { days })?;
self.0
.checked_add(jiff::SignedDuration::from_secs(seconds))
.map(Self)
.map_err(|_| TimeError::DateOverflow { days })
}
pub(crate) fn first_of_month(self) -> Self {
Self::new(self.year(), self.month(), 1).expect("the first day of a month always exists")
}
pub(crate) fn next_month_start(self) -> Result<Self, TimeError> {
let (year, month) = if self.month() == 12 {
(
self.year().checked_add(1).ok_or(TimeError::DateOverflow {
days: i64::from(self.month()),
})?,
1,
)
} else {
(self.year(), self.month() + 1)
};
Self::new(year, month, 1)
}
pub(crate) fn week_start(self, starts: Weekday) -> Result<Self, TimeError> {
let offset = i64::from(self.weekday().index()) - i64::from(starts.index());
self.plus_days(-offset.rem_euclid(7))
}
pub(crate) const fn as_jiff(self) -> civil::Date {
self.0
}
pub(crate) const fn from_jiff(date: civil::Date) -> Self {
Self(date)
}
}
impl fmt::Debug for Date {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for Date {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TimeOfDay {
hour: u8,
minute: u8,
}
impl TimeOfDay {
pub const MINUTES_PER_DAY: u16 = 24 * 60;
pub const MIDNIGHT: Self = Self { hour: 0, minute: 0 };
pub const fn new(hour: u8, minute: u8) -> Result<Self, TimeError> {
if hour >= 24 || minute >= 60 {
return Err(TimeError::TimeOfDayInvalid { hour, minute });
}
Ok(Self { hour, minute })
}
pub fn from_minute_of_day(minute_of_day: u16) -> Result<Self, TimeError> {
let out_of_range = TimeError::MinuteOfDayOutOfRange {
minute: i64::from(minute_of_day),
};
if minute_of_day >= Self::MINUTES_PER_DAY {
return Err(out_of_range);
}
Ok(Self {
hour: u8::try_from(minute_of_day / 60).map_err(|_| out_of_range.clone())?,
minute: u8::try_from(minute_of_day % 60).map_err(|_| out_of_range)?,
})
}
pub(crate) fn on(self, date: Date) -> civil::DateTime {
let hour = i8::try_from(self.hour).expect("a time-of-day hour is below 24");
let minute = i8::try_from(self.minute).expect("a time-of-day minute is below 60");
date.as_jiff().at(hour, minute, 0, 0)
}
pub(crate) fn from_jiff(time: civil::Time) -> Self {
Self {
hour: u8::try_from(time.hour()).expect("a jiff civil hour is below 24"),
minute: u8::try_from(time.minute()).expect("a jiff civil minute is below 60"),
}
}
#[must_use]
pub fn minute_of_day(&self) -> u16 {
u16::from(self.hour) * 60 + u16::from(self.minute)
}
#[must_use]
pub const fn hour(&self) -> u8 {
self.hour
}
#[must_use]
pub const fn minute(&self) -> u8 {
self.minute
}
}
impl fmt::Debug for TimeOfDay {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for TimeOfDay {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:02}:{:02}", self.hour(), self.minute())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Weekday {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}
impl Weekday {
pub const ALL: [Self; 7] = [
Self::Monday,
Self::Tuesday,
Self::Wednesday,
Self::Thursday,
Self::Friday,
Self::Saturday,
Self::Sunday,
];
pub fn iter() -> impl Iterator<Item = Self> {
Self::ALL.into_iter()
}
pub(crate) const fn index(self) -> u8 {
match self {
Self::Monday => 0,
Self::Tuesday => 1,
Self::Wednesday => 2,
Self::Thursday => 3,
Self::Friday => 4,
Self::Saturday => 5,
Self::Sunday => 6,
}
}
pub(crate) const fn bit(self) -> u8 {
1 << self.index()
}
}
impl fmt::Display for Weekday {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Monday => "mon",
Self::Tuesday => "tue",
Self::Wednesday => "wed",
Self::Thursday => "thu",
Self::Friday => "fri",
Self::Saturday => "sat",
Self::Sunday => "sun",
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Weekdays {
mask: u8,
}
impl Weekdays {
pub const NONE: Self = Self { mask: 0 };
pub const ALL: Self = Self { mask: 0b111_1111 };
#[allow(clippy::self_named_constructors)]
#[must_use]
pub const fn weekdays() -> Self {
Self {
mask: Weekday::Monday.bit()
| Weekday::Tuesday.bit()
| Weekday::Wednesday.bit()
| Weekday::Thursday.bit()
| Weekday::Friday.bit(),
}
}
#[must_use]
pub fn single(day: Weekday) -> Self {
Self { mask: day.bit() }
}
#[must_use]
pub fn list(days: impl IntoIterator<Item = Weekday>) -> Self {
Self {
mask: days.into_iter().fold(0, |mask, day| mask | day.bit()),
}
}
#[must_use]
pub fn range(first: Weekday, last: Weekday) -> Self {
let mut mask = 0u8;
let mut index = first.index();
loop {
mask |= 1 << index;
if index == last.index() {
break;
}
index = (index + 1) % 7;
}
Self { mask }
}
#[must_use]
pub const fn contains(&self, day: Weekday) -> bool {
self.mask & day.bit() != 0
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.mask == 0
}
pub fn iter(&self) -> impl Iterator<Item = Weekday> + '_ {
Weekday::iter().filter(|day| self.contains(*day))
}
}
impl fmt::Debug for Weekdays {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut first = true;
for day in self.iter() {
if !first {
f.write_str(",")?;
}
write!(f, "{day}")?;
first = false;
}
if first {
f.write_str("<none>")?;
}
Ok(())
}
}
pub type WorkingDays = Weekdays;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LocalDateTime {
date: Date,
time: TimeOfDay,
}
impl LocalDateTime {
#[must_use]
pub const fn new(date: Date, time: TimeOfDay) -> Self {
Self { date, time }
}
#[must_use]
pub const fn date(&self) -> Date {
self.date
}
#[must_use]
pub const fn time(&self) -> TimeOfDay {
self.time
}
}
impl fmt::Debug for LocalDateTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for LocalDateTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}T{}", self.date, self.time)
}
}
#[cfg(test)]
mod tests {
use super::{Date, TimeOfDay, Weekday};
use crate::time::TimeError;
#[test]
fn leap_days_follow_the_calendar() {
assert!(Date::new(2028, 2, 29).is_ok());
assert!(Date::new(2027, 2, 29).is_err());
assert!("2027-02-29".parse::<jiff::civil::Date>().is_err());
assert_eq!(
Date::new(2027, 2, 29),
Err(TimeError::DateInvalid {
year: 2027,
month: 2,
day: 29
})
);
assert_eq!(Date::new(2028, 2, 29).unwrap().to_string(), "2028-02-29");
}
#[test]
fn weekdays_follow_the_date() {
assert_eq!(Date::new(2027, 3, 8).unwrap().weekday(), Weekday::Monday);
assert_eq!(Date::new(2027, 3, 12).unwrap().weekday(), Weekday::Friday);
assert_eq!(Date::new(2027, 3, 13).unwrap().weekday(), Weekday::Saturday);
assert_eq!(Date::new(2027, 3, 14).unwrap().weekday(), Weekday::Sunday);
}
#[test]
fn plus_days_crosses_month_and_year_boundaries() {
let date = Date::new(2027, 12, 31).unwrap();
assert_eq!(date.plus_days(1).unwrap(), Date::new(2028, 1, 1).unwrap());
assert_eq!(
Date::new(2028, 3, 1).unwrap().plus_days(-1).unwrap(),
Date::new(2028, 2, 29).unwrap()
);
assert_eq!(date.plus_days(0).unwrap(), date);
}
#[test]
fn errors_carry_stable_codes() {
assert_eq!(
TimeError::DateInvalid {
year: 2027,
month: 2,
day: 29
}
.code(),
"date_invalid"
);
assert_eq!(
TimeError::TimeOfDayInvalid {
hour: 24,
minute: 0
}
.code(),
"time_of_day_invalid"
);
assert_eq!(
TimeError::MinuteOfDayOutOfRange { minute: 1440 }.code(),
"minute_of_day_out_of_range"
);
}
#[test]
fn times_of_day_round_trip_through_minutes() {
assert_eq!(
TimeOfDay::new(9, 30).unwrap().minute_of_day(),
570,
"half past nine is 570 minutes into the day"
);
assert_eq!(
TimeOfDay::from_minute_of_day(570).unwrap(),
TimeOfDay::new(9, 30).unwrap()
);
assert_eq!(TimeOfDay::MINUTES_PER_DAY, 1440);
assert_eq!(
TimeOfDay::new(23, 59).unwrap().minute_of_day(),
TimeOfDay::MINUTES_PER_DAY - 1
);
assert_eq!(TimeOfDay::MIDNIGHT.to_string(), "00:00");
assert!(TimeOfDay::from_minute_of_day(1440).is_err());
assert!(TimeOfDay::new(12, 60).is_err());
}
}