use crate::time::error::TimeError;
use crate::time::{Date, Duration, Instant, WorkingDays, Zone};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkingCalendar {
zone: Zone,
working_days: WorkingDays,
holidays: Vec<Date>,
}
impl WorkingCalendar {
pub fn new(
zone: Zone,
working_days: WorkingDays,
mut holidays: Vec<Date>,
) -> Result<Self, TimeError> {
if working_days.is_empty() {
return Err(TimeError::WorkingDaysEmpty);
}
holidays.sort_unstable();
holidays.dedup();
Ok(Self {
zone,
working_days,
holidays,
})
}
#[must_use]
pub fn zone(&self) -> &Zone {
&self.zone
}
#[must_use]
pub const fn working_days(&self) -> WorkingDays {
self.working_days
}
#[must_use]
pub fn holidays(&self) -> &[Date] {
&self.holidays
}
#[must_use]
pub fn is_working_day(&self, date: Date) -> bool {
self.working_days.contains(date.weekday()) && self.holidays.binary_search(&date).is_err()
}
fn working_day_limit(
&self,
date: Date,
count: u32,
ceiling: Date,
) -> Result<Option<Date>, TimeError> {
if count == 0 {
return Ok(Some(date));
}
let mut current = date;
let mut remaining = count;
loop {
current = current.plus_days(1)?;
if current > ceiling {
return Ok(None);
}
if self.is_working_day(current) {
remaining -= 1;
if remaining == 0 {
return Ok(Some(current));
}
}
}
}
pub(crate) fn working_days_bound(
&self,
now: Instant,
count: u32,
) -> Result<StartBound, TimeError> {
self.working_days_bound_until(now, count, Instant::MAX)
}
pub(crate) fn working_days_bound_until(
&self,
now: Instant,
count: u32,
horizon_end: Instant,
) -> Result<StartBound, TimeError> {
let today = now.zoned(self.zone()).date();
let latest = Instant::MAX.zoned(self.zone()).date();
let ceiling = horizon_end
.zoned(self.zone())
.date()
.plus_days(1)
.unwrap_or(latest)
.min(latest);
let limit = match self.working_day_limit(today, count, ceiling)? {
Some(date) => StartLimit::Date(date),
None => StartLimit::Unbounded,
};
let zone = self.zone().clone();
let fast = FastBound::resolve(&limit, &zone);
Ok(StartBound { limit, zone, fast })
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Horizon {
Duration(Duration),
Days(u32),
WorkingDays {
count: u32,
calendar: WorkingCalendar,
},
Date(Date),
}
impl Horizon {
pub fn bound(&self, now: Instant, event_zone: &Zone) -> Result<StartBound, TimeError> {
let today_in = |zone: &Zone| now.zoned(zone).date();
let bound = match self {
Self::Duration(duration) => {
StartLimit::instant(now.minutes().saturating_add(duration.minutes()))?
}
Self::Days(days) => match today_in(event_zone).plus_days(i64::from(*days)) {
Ok(date) => StartLimit::Date(date),
Err(TimeError::DateOverflow { .. }) => StartLimit::Unbounded,
Err(err) => return Err(err),
},
Self::WorkingDays { count, calendar } => {
let today = today_in(calendar.zone());
let latest = Instant::MAX.zoned(calendar.zone()).date();
match calendar.working_day_limit(today, *count, latest)? {
Some(date) => StartLimit::Date(date),
None => StartLimit::Unbounded,
}
}
Self::Date(date) => StartLimit::Date(*date),
};
let zone = match self {
Self::WorkingDays { calendar, .. } => calendar.zone().clone(),
_ => event_zone.clone(),
};
let fast = FastBound::resolve(&bound, &zone);
Ok(StartBound {
limit: bound,
zone,
fast,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StartBound {
limit: StartLimit,
zone: Zone,
fast: FastBound,
}
impl StartBound {
#[must_use]
pub fn allows(&self, start: Instant) -> bool {
match self.fast {
FastBound::Unbounded => true,
FastBound::Never => false,
FastBound::UpTo(latest) => start <= latest,
FastBound::ByDate(latest) => start.zoned(&self.zone).date() <= latest,
}
}
#[must_use]
pub fn is_stricter_than(&self, other: &Self) -> bool {
self.strictness() < other.strictness()
}
fn strictness(&self) -> Strictness {
match &self.limit {
StartLimit::Unbounded => Strictness::Unlimited,
StartLimit::Instant(latest) => Strictness::UpTo(*latest),
StartLimit::Date(latest) => {
let first_supported = Instant::MIN.zoned(&self.zone).date();
if *latest < first_supported {
return Strictness::Never;
}
if *latest >= Instant::MAX.zoned(&self.zone).date() {
return Strictness::Unlimited;
}
match self.zone.last_instant_on(*latest) {
Ok(Some(last)) => Strictness::UpTo(last),
Ok(None) => Strictness::Never,
Err(_) => Strictness::Unlimited,
}
}
}
}
}
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum Strictness {
Never,
UpTo(Instant),
Unlimited,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FastBound {
Unbounded,
Never,
UpTo(Instant),
ByDate(Date),
}
impl FastBound {
fn resolve(limit: &StartLimit, zone: &Zone) -> Self {
match limit {
StartLimit::Unbounded => Self::Unbounded,
StartLimit::Instant(latest) => Self::UpTo(*latest),
StartLimit::Date(latest) => Self::resolve_date(*latest, zone),
}
}
fn resolve_date(latest: Date, zone: &Zone) -> Self {
let Ok(next) = latest.plus_days(1) else {
return Self::Unbounded;
};
let Ok(start_of_next) = zone.day_start(next) else {
return Self::ByDate(latest);
};
let probe_until = Instant::from_minutes(
start_of_next
.minutes()
.saturating_add(48 * 60)
.min(Instant::MAX.minutes()),
)
.unwrap_or(Instant::MAX);
let Ok(transitions) = zone.transition_instants(start_of_next, probe_until) else {
return Self::ByDate(latest);
};
if transitions
.iter()
.any(|transition| zone.zoned(*transition).date() <= latest)
{
return Self::ByDate(latest);
}
match Instant::from_minutes(start_of_next.minutes() - 1) {
Ok(last) => Self::UpTo(last),
Err(_) => Self::Never,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum StartLimit {
Unbounded,
Instant(Instant),
Date(Date),
}
impl StartLimit {
fn instant(latest_minutes: i64) -> Result<Self, TimeError> {
match Instant::from_minutes(latest_minutes) {
Ok(instant) => Ok(Self::Instant(instant)),
Err(TimeError::InstantOutOfRange { .. }) => Ok(Self::Unbounded),
Err(err) => Err(err),
}
}
}
#[cfg(test)]
mod tests {
use super::{Horizon, StartBound, WorkingCalendar, WorkingDays};
use crate::time::{
Date, Duration, Instant, LocalResolution, TimeError, TimeOfDay, Weekday, Zone,
};
fn utc_instant(y: i16, m: i8, d: i8, hour: u8, minute: u8) -> Instant {
let LocalResolution::Unique(instant) = Zone::utc()
.resolve_local(
Date::new(y, m, d).unwrap(),
TimeOfDay::new(hour, minute).unwrap(),
)
.unwrap()
else {
panic!("UTC has no transitions")
};
instant
}
fn org() -> WorkingCalendar {
WorkingCalendar::new(
Zone::utc(),
WorkingDays::weekdays(),
vec![
Date::new(2027, 1, 1).unwrap(),
Date::new(2027, 12, 24).unwrap(),
Date::new(2027, 12, 24).unwrap(),
],
)
.unwrap()
}
fn allows(horizon: &Horizon, start: Instant, now: Instant) -> bool {
let bound: StartBound = horizon.bound(now, &Zone::utc()).unwrap();
bound.allows(start)
}
#[test]
fn working_days_are_weekdays_less_holidays() {
let calendar = org();
assert_eq!(calendar.holidays().len(), 2);
assert!(calendar.is_working_day(Date::new(2027, 3, 9).unwrap()));
assert!(!calendar.is_working_day(Date::new(2027, 3, 13).unwrap()));
assert!(!calendar.is_working_day(Date::new(2027, 12, 24).unwrap()));
assert!(
WorkingDays::list([Weekday::Saturday, Weekday::Sunday]).contains(Weekday::Saturday)
);
assert_eq!(
format!("{:?}", WorkingDays::weekdays()),
"mon,tue,wed,thu,fri"
);
}
#[test]
fn working_day_counts_skip_weekends_and_holidays() {
let calendar = org();
let horizon = Horizon::WorkingDays {
count: 3,
calendar: calendar.clone(),
};
let now = utc_instant(2027, 3, 12, 9, 0);
assert!(allows(&horizon, utc_instant(2027, 3, 13, 12, 0), now));
assert!(allows(&horizon, utc_instant(2027, 3, 17, 23, 59), now));
assert!(!allows(&horizon, utc_instant(2027, 3, 18, 0, 0), now));
let horizon = Horizon::WorkingDays { count: 2, calendar };
let now = utc_instant(2027, 12, 30, 9, 0);
assert!(allows(&horizon, utc_instant(2028, 1, 3, 23, 0), now));
assert!(!allows(&horizon, utc_instant(2028, 1, 4, 0, 0), now));
}
#[test]
fn a_zero_day_horizon_ends_the_horizon_today() {
let now = utc_instant(2027, 3, 10, 9, 0);
let horizon = Horizon::WorkingDays {
count: 0,
calendar: org(),
};
assert!(allows(&horizon, utc_instant(2027, 3, 10, 23, 59), now));
assert!(!allows(&horizon, utc_instant(2027, 3, 11, 0, 0), now));
}
#[test]
fn a_calendar_working_no_weekday_is_rejected() {
let error = WorkingCalendar::new(Zone::utc(), WorkingDays::NONE, Vec::new()).unwrap_err();
assert_eq!(error, TimeError::WorkingDaysEmpty);
assert_eq!(error.code(), "working_days_empty");
}
#[test]
fn bounds_compare_by_the_last_start_they_allow() {
let zone = Zone::utc();
let now = utc_instant(2027, 3, 9, 0, 0);
let dates = Horizon::Date(Date::new(2027, 3, 11).unwrap())
.bound(now, &zone)
.unwrap();
let hours = Horizon::Duration(Duration::from_hours_minutes(24, 0))
.bound(now, &zone)
.unwrap();
assert!(hours.is_stricter_than(&dates));
assert!(!dates.is_stricter_than(&hours));
let unrestricted = Horizon::Days(u32::MAX).bound(now, &zone).unwrap();
assert!(dates.is_stricter_than(&unrestricted));
assert!(hours.is_stricter_than(&unrestricted));
assert!(!unrestricted.is_stricter_than(&dates));
assert!(!dates.is_stricter_than(&dates), "equals are not stricter");
}
#[cfg(feature = "bundled-tzdb")]
#[test]
fn a_date_maximum_ends_where_the_next_local_day_begins() {
let santiago = crate::time::TimeZoneDatabase::bundled()
.unwrap()
.zone("America/Santiago")
.unwrap();
let now = utc_instant(2027, 9, 1, 0, 0);
let dates = Horizon::Date(Date::new(2027, 9, 4).unwrap())
.bound(now, &santiago)
.unwrap();
let first_of_the_5th = utc_instant(2027, 9, 5, 4, 0);
let ends_at = |end: Instant| {
Horizon::Duration(Duration::from_minutes(
u32::try_from(end.minutes() - now.minutes()).unwrap(),
))
.bound(now, &santiago)
.unwrap()
};
let one_minute_before = Instant::from_minutes(first_of_the_5th.minutes() - 1).unwrap();
assert!(
!ends_at(one_minute_before).is_stricter_than(&dates),
"a duration ending where the date maximum ends is not stricter"
);
assert!(
!dates.is_stricter_than(&ends_at(one_minute_before)),
"and neither is the date maximum"
);
assert!(
dates.is_stricter_than(&ends_at(first_of_the_5th)),
"the date maximum stops one minute before the 5th begins"
);
assert!(
ends_at(Instant::from_minutes(one_minute_before.minutes() - 1).unwrap())
.is_stricter_than(&dates)
);
}
#[test]
fn a_horizon_past_the_calendar_bounds_nothing() {
let now = utc_instant(2027, 3, 9, 10, 0);
for horizon in [
Horizon::Days(u32::MAX),
Horizon::WorkingDays {
count: u32::MAX,
calendar: org(),
},
] {
assert!(allows(&horizon, Instant::MAX, now), "{horizon:?}");
}
}
#[test]
fn durations_compare_instants() {
let now = utc_instant(2027, 3, 9, 10, 0);
let horizon = Horizon::Duration(Duration::from_hours_minutes(4, 0));
assert!(allows(&horizon, now, now));
assert!(allows(&horizon, utc_instant(2027, 3, 9, 14, 0), now));
assert!(!allows(&horizon, utc_instant(2027, 3, 9, 14, 1), now));
}
#[test]
fn the_rest_of_today_is_inside_a_working_day_horizon_without_being_counted() {
let horizon = Horizon::WorkingDays {
count: 3,
calendar: org(),
};
let now = utc_instant(2027, 3, 10, 9, 0);
assert!(allows(&horizon, utc_instant(2027, 3, 10, 18, 0), now));
assert!(allows(&horizon, utc_instant(2027, 3, 15, 12, 0), now));
assert!(!allows(&horizon, utc_instant(2027, 3, 16, 0, 0), now));
}
#[test]
fn calendar_days_cross_leap_days() {
let horizon = Horizon::Days(2);
let now = utc_instant(2028, 2, 28, 12, 0);
assert!(allows(&horizon, utc_instant(2028, 3, 1, 23, 0), now));
assert!(!allows(&horizon, utc_instant(2028, 3, 2, 0, 0), now));
let horizon = Horizon::Date(Date::new(2028, 2, 29).unwrap());
assert!(allows(&horizon, utc_instant(2028, 2, 29, 23, 59), now));
assert!(!allows(&horizon, utc_instant(2028, 3, 1, 0, 0), now));
}
#[test]
fn a_zero_day_horizon_ends_at_the_end_of_today() {
let horizon = Horizon::Days(0);
let now = utc_instant(2027, 3, 9, 23, 30);
assert!(allows(&horizon, utc_instant(2027, 3, 9, 23, 45), now));
assert!(!allows(&horizon, utc_instant(2027, 3, 10, 0, 0), now));
}
}