use std::collections::BTreeSet;
use crate::time::error::TimeError;
use crate::time::{Date, Instant, Zone};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ZonePeriod {
zone: Zone,
from: Instant,
until: Instant,
}
impl ZonePeriod {
pub fn new(zone: Zone, from: Instant, until: Instant) -> Result<Self, TimeError> {
if from >= until {
return Err(TimeError::ZonePeriodEmpty { from, until });
}
Ok(Self { zone, from, until })
}
#[must_use]
pub fn zone(&self) -> &Zone {
&self.zone
}
#[must_use]
pub const fn from(&self) -> Instant {
self.from
}
#[must_use]
pub const fn until(&self) -> Instant {
self.until
}
#[must_use]
pub fn contains(&self, instant: Instant) -> bool {
self.from <= instant && instant < self.until
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ZoneSchedule {
home: Zone,
periods: Vec<ZonePeriod>,
}
impl ZoneSchedule {
#[must_use]
pub fn fixed(zone: Zone) -> Self {
Self {
home: zone,
periods: Vec::new(),
}
}
pub fn new(home: Zone, mut periods: Vec<ZonePeriod>) -> Result<Self, TimeError> {
periods.sort_by_key(ZonePeriod::from);
for pair in periods.windows(2) {
let (earlier, later) = (&pair[0], &pair[1]);
if later.from < earlier.until {
return Err(TimeError::ZonePeriodsOverlap { from: later.from });
}
}
Ok(Self { home, periods })
}
#[must_use]
pub fn home(&self) -> &Zone {
&self.home
}
#[must_use]
pub fn periods(&self) -> &[ZonePeriod] {
&self.periods
}
#[must_use]
pub fn zone_at(&self, instant: Instant) -> &Zone {
let index = self
.periods
.partition_point(|period| period.until <= instant);
match self.periods.get(index) {
Some(period) if period.contains(instant) => &period.zone,
_ => &self.home,
}
}
pub(crate) fn slices(&self, from: Instant, until: Instant) -> Vec<(Instant, Instant)> {
if from >= until {
return Vec::new();
}
let first = self.periods.partition_point(|period| period.until <= from);
let mut boundaries: Vec<Instant> = Vec::with_capacity(2);
boundaries.push(from);
for period in &self.periods[first..] {
if period.from >= until {
break;
}
for boundary in [period.from, period.until] {
if from < boundary && boundary < until && boundaries.last() != Some(&boundary) {
boundaries.push(boundary);
}
}
}
boundaries
.iter()
.enumerate()
.map(|(index, &start)| {
let end = boundaries.get(index + 1).copied().unwrap_or(until);
(start, end)
})
.collect()
}
pub(crate) fn legs(
&self,
from: Instant,
until: Instant,
) -> impl Iterator<Item = (&Zone, Instant, Instant)> + '_ {
let mut cursor = from;
let mut index = self.periods.partition_point(|period| period.until <= from);
std::iter::from_fn(move || {
if cursor >= until {
return None;
}
let start = cursor;
match self.periods.get(index) {
Some(period) if period.from <= cursor => {
cursor = period.until.min(until);
index += 1;
Some((&period.zone, start, cursor))
}
Some(period) => {
cursor = period.from.min(until);
Some((&self.home, start, cursor))
}
None => {
cursor = until;
Some((&self.home, start, until))
}
}
})
}
pub(crate) fn date_jumps(&self, from: Instant, until: Instant) -> Result<Vec<i64>, TimeError> {
let mut jumps: Vec<i64> = Vec::new();
let mut zones: Vec<&Zone> = vec![&self.home];
for period in &self.periods {
if from < period.until && period.from < until {
if from < period.from {
jumps.push(period.from.minutes());
}
if period.until < until {
jumps.push(period.until.minutes());
}
if !zones.iter().any(|seen| seen.name() == period.zone.name()) {
zones.push(&period.zone);
}
}
}
for zone in zones {
for transition in zone.transition_instants(from, until)? {
jumps.push(transition.minutes());
}
}
jumps.sort_unstable();
jumps.dedup();
Ok(jumps)
}
pub(crate) fn for_each_date_segment(
&self,
jumps: &[i64],
from: i64,
until: i64,
mut visit: impl FnMut(i64, i64, Date),
) {
let mut minute = from;
while minute < until {
let Ok(instant) = Instant::from_minutes(minute) else {
break;
};
let zone = self.zone_at(instant);
let date = zone.zoned(instant).date();
let day_end = date
.plus_days(1)
.ok()
.and_then(|next| zone.day_start(next).ok())
.map_or(until, |end| end.minutes());
let next = jumps.partition_point(|jump| *jump <= minute);
let jump_end = jumps.get(next).copied().unwrap_or(i64::MAX);
let stop = day_end.min(jump_end).max(minute + 1).min(until);
visit(minute, stop, date);
minute = stop;
}
}
pub(crate) fn dates_in(
&self,
jumps: &[i64],
from: i64,
until: i64,
dates: &mut BTreeSet<Date>,
) {
self.for_each_date_segment(jumps, from, until, |_, _, date| {
dates.insert(date);
});
}
}
#[cfg(test)]
mod tests {
use super::{ZonePeriod, ZoneSchedule};
use crate::time::{Instant, TimeError, Zone};
fn instant(hour: i64) -> Instant {
Instant::from_minutes(Instant::MIN.minutes() + hour * 60).unwrap()
}
#[test]
fn empty_periods_fall_back_to_the_home_zone() {
let home = Zone::utc();
let schedule = ZoneSchedule::new(home.clone(), Vec::new()).unwrap();
assert_eq!(schedule.zone_at(Instant::MIN), &home);
assert_eq!(schedule.zone_at(Instant::MAX), &home);
assert!(schedule.periods().is_empty());
assert_eq!(schedule.home(), &home);
}
#[test]
fn overlapping_periods_are_rejected_whatever_order_they_arrive_in() {
let zone = Zone::utc();
let error = ZoneSchedule::new(
zone.clone(),
vec![
ZonePeriod::new(zone.clone(), instant(5), instant(15)).unwrap(),
ZonePeriod::new(zone.clone(), instant(0), instant(6)).unwrap(),
],
)
.unwrap_err();
assert_eq!(error, TimeError::ZonePeriodsOverlap { from: instant(5) });
assert_eq!(error.code(), "zone_periods_overlap");
}
#[test]
fn adjacent_periods_join_exactly() {
let zone = Zone::utc();
let schedule = ZoneSchedule::new(
zone.clone(),
vec![
ZonePeriod::new(zone.clone(), instant(9), instant(21)).unwrap(),
ZonePeriod::new(zone.clone(), instant(21), instant(30)).unwrap(),
],
)
.unwrap();
assert_eq!(schedule.periods().len(), 2);
assert!(schedule.periods()[0].contains(instant(20)));
assert!(!schedule.periods()[0].contains(instant(21)));
assert!(schedule.periods()[1].contains(instant(21)));
}
#[test]
fn slices_split_on_the_period_edges_inside_the_range_only() {
let zone = Zone::utc();
let other = Zone::utc();
let schedule = ZoneSchedule::new(
zone.clone(),
vec![
ZonePeriod::new(other.clone(), instant(0), instant(9)).unwrap(),
ZonePeriod::new(other.clone(), instant(9), instant(30)).unwrap(),
],
)
.unwrap();
assert_eq!(
schedule.slices(instant(5), instant(20)),
vec![(instant(5), instant(9)), (instant(9), instant(20)),]
);
assert_eq!(
schedule.slices(instant(0), instant(30)),
vec![(instant(0), instant(9)), (instant(9), instant(30))]
);
assert_eq!(
schedule.slices(instant(9), instant(30)),
vec![(instant(9), instant(30))]
);
assert_eq!(
schedule.slices(instant(40), instant(50)),
vec![(instant(40), instant(50))]
);
assert!(schedule.slices(instant(20), instant(20)).is_empty());
}
#[test]
fn a_period_must_cover_at_least_one_instant() {
let zone = Zone::utc();
assert_eq!(
ZonePeriod::new(zone.clone(), instant(5), instant(5)),
Err(TimeError::ZonePeriodEmpty {
from: instant(5),
until: instant(5)
})
);
assert_eq!(
TimeError::ZonePeriodEmpty {
from: instant(5),
until: instant(5)
}
.code(),
"zone_period_empty"
);
}
}
#[cfg(all(test, feature = "bundled-tzdb"))]
mod bundled_tests {
use super::{ZonePeriod, ZoneSchedule};
use crate::time::{Instant, TimeZoneDatabase};
use std::collections::BTreeSet;
#[test]
fn legs_are_the_slices_with_the_zone_in_force_at_each_start() {
let db = TimeZoneDatabase::bundled().unwrap();
let utc = crate::time::Zone::utc();
let tokyo = db.zone("Asia/Tokyo").unwrap();
let new_york = db.zone("America/New_York").unwrap();
let hour = |hours: i64| Instant::from_minutes(Instant::MIN.minutes() + hours * 60).unwrap();
let schedule = ZoneSchedule::new(
utc.clone(),
vec![
ZonePeriod::new(tokyo.clone(), hour(2), hour(6)).unwrap(),
ZonePeriod::new(new_york.clone(), hour(6), hour(10)).unwrap(),
ZonePeriod::new(tokyo.clone(), hour(14), hour(20)).unwrap(),
],
)
.unwrap();
for (from, until) in [
(hour(0), hour(24)),
(hour(3), hour(8)),
(hour(6), hour(6)),
(hour(5), hour(21)),
(hour(22), hour(30)),
(hour(0), hour(2)),
(hour(20), hour(21)),
] {
let expected: Vec<_> = schedule
.slices(from, until)
.into_iter()
.map(|(start, end)| (schedule.zone_at(start), start, end))
.collect();
let walked: Vec<_> = schedule.legs(from, until).collect();
assert_eq!(walked, expected, "{from:?}..{until:?}");
}
}
#[test]
fn the_date_walk_collects_every_local_date_a_transition_repeats() {
let db = TimeZoneDatabase::bundled().unwrap();
let mut checked = 0usize;
for name in db.available_names() {
let zone = db.zone(&name).unwrap();
let schedule = ZoneSchedule::fixed(zone.clone());
let repeats = zone
.transition_instants(Instant::MIN, Instant::MAX)
.unwrap()
.into_iter()
.filter(|transition| {
Instant::from_minutes(transition.minutes() - 1).is_ok_and(|before| {
zone.zoned(*transition).date() < zone.zoned(before).date()
})
})
.collect::<Vec<_>>();
for transition in repeats {
for offset in [-2_880i64, -1_440, -120, -61, -60, -30, -1, 0, 1, 60] {
let from = transition.minutes() + offset;
let until = from + 600;
let (Ok(start), Ok(end)) =
(Instant::from_minutes(from), Instant::from_minutes(until))
else {
continue;
};
let jumps = schedule.date_jumps(start, end).unwrap();
let mut walked = BTreeSet::new();
schedule.dates_in(&jumps, from, until, &mut walked);
let mut expected = BTreeSet::new();
for minute in from..until {
let Ok(instant) = Instant::from_minutes(minute) else {
continue;
};
expected.insert(zone.zoned(instant).date());
}
checked += 1;
assert_eq!(
walked, expected,
"{name}: the walk from one minute before {transition} plus {offset}"
);
}
}
}
assert!(
checked > 0,
"the bundled database no longer holds a transition that repeats a local \
date, so this walk has nothing left to prove"
);
}
#[test]
fn the_date_walk_stops_at_a_period_zones_repeated_date() {
let db = TimeZoneDatabase::bundled().unwrap();
let home = db.zone("UTC").unwrap();
let mut checked = 0usize;
for name in db.available_names() {
let zone = db.zone(&name).unwrap();
let repeats = zone
.transition_instants(Instant::MIN, Instant::MAX)
.unwrap()
.into_iter()
.filter(|transition| {
Instant::from_minutes(transition.minutes() - 1).is_ok_and(|before| {
zone.zoned(*transition).date() < zone.zoned(before).date()
})
})
.collect::<Vec<_>>();
for transition in repeats {
let (Ok(leg_from), Ok(leg_until)) = (
Instant::from_minutes(transition.minutes() - 2 * 1_440),
Instant::from_minutes(transition.minutes() + 2 * 1_440),
) else {
continue;
};
let schedule = ZoneSchedule::new(
home.clone(),
vec![ZonePeriod::new(zone.clone(), leg_from, leg_until).unwrap()],
)
.unwrap();
for offset in [-1_440i64, -61, -1, 0, 1, 60] {
let from = transition.minutes() + offset;
let until = from + 600;
let (Ok(start), Ok(end)) =
(Instant::from_minutes(from), Instant::from_minutes(until))
else {
continue;
};
let jumps = schedule.date_jumps(start, end).unwrap();
let mut walked = BTreeSet::new();
schedule.dates_in(&jumps, from, until, &mut walked);
let mut expected = BTreeSet::new();
for minute in from..until {
let Ok(instant) = Instant::from_minutes(minute) else {
continue;
};
expected.insert(schedule.zone_at(instant).zoned(instant).date());
}
checked += 1;
assert_eq!(
walked, expected,
"{name} visited: the walk from one minute before {transition} \
plus {offset} loses the date the leg's zone repeats"
);
}
}
}
assert!(
checked > 0,
"the bundled database no longer holds a transitional zone to visit, so \
this walk has nothing left to prove"
);
}
#[test]
fn the_date_walk_neither_invents_nor_loses_a_skipped_date() {
let db = TimeZoneDatabase::bundled().unwrap();
let mut checked = 0usize;
for name in db.available_names() {
let zone = db.zone(&name).unwrap();
let schedule = ZoneSchedule::fixed(zone.clone());
let skips = zone
.transition_instants(Instant::MIN, Instant::MAX)
.unwrap()
.into_iter()
.filter(|transition| {
Instant::from_minutes(transition.minutes() - 1).is_ok_and(|before| {
zone.zoned(*transition)
.date()
.plus_days(-1)
.is_ok_and(|previous| zone.zoned(before).date() < previous)
})
})
.collect::<Vec<_>>();
for transition in skips {
for offset in [-1_440i64, -61, -1, 0, 60] {
let from = transition.minutes() + offset;
let until = from + 240;
let (Ok(start), Ok(end)) =
(Instant::from_minutes(from), Instant::from_minutes(until))
else {
continue;
};
let jumps = schedule.date_jumps(start, end).unwrap();
let mut walked = BTreeSet::new();
schedule.dates_in(&jumps, from, until, &mut walked);
let mut expected = BTreeSet::new();
for minute in from..until {
let Ok(instant) = Instant::from_minutes(minute) else {
continue;
};
expected.insert(zone.zoned(instant).date());
}
checked += 1;
assert_eq!(
walked, expected,
"{name}: the walk from one minute before {transition} plus \
{offset} invents or loses a date across the skipped day"
);
}
}
}
assert!(
checked > 0,
"the bundled database no longer holds a transition that skips a civil \
date, so this walk has nothing left to prove"
);
}
}