use crate::intervals::{IntervalSet, Span};
use crate::time::{Date, Instant, TimeError, TimeOfDay, Zone, ZoneSchedule};
pub(crate) trait BreakpointSource {
fn member(&self, instant: Instant, zone: &Zone) -> bool;
fn breakpoints(
&self,
zone: &Zone,
start: Instant,
end: Instant,
) -> Result<Vec<Instant>, TimeError>;
}
pub(crate) fn build(
source: &impl BreakpointSource,
schedule: &ZoneSchedule,
from: Instant,
until: Instant,
) -> Result<IntervalSet, TimeError> {
if from >= until {
return Ok(IntervalSet::new());
}
let mut spans = Vec::new();
for (slice_start, slice_end) in schedule.slices(from, until) {
let zone = schedule.zone_at(slice_start);
let mut points = vec![slice_start];
for point in source.breakpoints(zone, slice_start, slice_end)? {
if slice_start < point && point < slice_end {
points.push(point);
}
}
points.sort_unstable();
points.dedup();
for (index, &segment_start) in points.iter().enumerate() {
let segment_end = points.get(index + 1).copied().unwrap_or(slice_end);
if source.member(segment_start, zone) {
spans.push(
Span::new(segment_start.minutes(), segment_end.minutes()).expect(
"a slice spans at least one minute and its breakpoints lie inside it",
),
);
}
}
}
Ok(IntervalSet::from_spans(spans))
}
pub(crate) fn build_minutes(
source: &impl BreakpointSource,
schedule: &ZoneSchedule,
range: Span,
) -> Result<IntervalSet, TimeError> {
let from = Instant::from_minutes(range.start().max(Instant::MIN.minutes()))?;
let until = Instant::from_minutes(range.end().min(Instant::MAX.minutes()))?;
let mut minutes = build(source, schedule, from, until)?;
if range.end() > Instant::MAX.minutes()
&& source.member(Instant::MAX, schedule.zone_at(Instant::MAX))
{
let last = Span::new(Instant::MAX.minutes(), Instant::MAX.minutes() + 1)
.expect("the last supported minute is a non-empty span");
minutes = minutes.union(&IntervalSet::from_spans(vec![last]));
}
Ok(minutes)
}
pub(crate) fn push_local(
instants: &mut Vec<Instant>,
zone: &Zone,
date: Date,
time: TimeOfDay,
) -> Result<(), TimeError> {
instants.extend(zone.local_instants(date, time)?);
Ok(())
}
pub(crate) fn dates_covering(
zone: &Zone,
start: Instant,
end: Instant,
transitions: &[Instant],
) -> (Date, Date) {
let mut earliest = zone.zoned(start).date();
let mut latest = earliest;
let mut observe = |instant: Instant| {
let date = zone.zoned(instant).date();
earliest = earliest.min(date);
latest = latest.max(date);
};
for &transition in transitions {
observe(transition);
observe(
Instant::from_minutes(transition.minutes() - 1)
.expect("a transition inside the slice has a representable minute before it"),
);
}
observe(
Instant::from_minutes(end.minutes() - 1)
.expect("a slice ends at least one minute after it starts"),
);
(earliest, latest)
}
#[cfg(all(test, feature = "bundled-tzdb"))]
mod tests {
use super::dates_covering;
use crate::time::{Date, Instant, LocalResolution, TimeOfDay, TimeZoneDatabase, Zone};
fn utc(year: i16, month: i8, day: i8, hour: u8) -> Instant {
let date = Date::new(year, month, day).unwrap();
let LocalResolution::Unique(instant) = Zone::utc()
.resolve_local(date, TimeOfDay::new(hour, 0).unwrap())
.unwrap()
else {
panic!("UTC has no transitions")
};
instant
}
#[test]
fn the_covered_dates_are_exactly_the_local_dates_inside_the_slice() {
let db = TimeZoneDatabase::bundled().unwrap();
let slices = [
(
"America/Sao_Paulo",
utc(2018, 2, 17, 12),
utc(2018, 2, 18, 12),
),
("America/Santiago", utc(2027, 9, 4, 12), utc(2027, 9, 5, 12)),
("America/New_York", utc(2027, 11, 7, 0), utc(2027, 11, 8, 0)),
(
"Australia/Lord_Howe",
utc(2027, 4, 3, 0),
utc(2027, 4, 4, 0),
),
("Pacific/Apia", utc(2011, 12, 30, 0), utc(2011, 12, 31, 0)),
(
"Pacific/Kiritimati",
utc(1994, 12, 30, 0),
utc(1995, 1, 1, 0),
),
(
"Europe/Moscow",
utc(2014, 10, 25, 12),
utc(2014, 10, 26, 12),
),
(
"Antarctica/Troll",
utc(2027, 3, 27, 12),
utc(2027, 3, 28, 12),
),
];
for (name, from, until) in slices {
let zone = db.zone(name).unwrap();
let transitions = zone.transition_instants(from, until).unwrap();
assert!(
!transitions.is_empty(),
"{name}: the fixture must cross a transition"
);
let (first, last) = dates_covering(&zone, from, until, &transitions);
let mut earliest = None;
let mut latest = None;
for minute in from.minutes()..until.minutes() {
let date = zone.zoned(Instant::from_minutes(minute).unwrap()).date();
earliest = Some(earliest.map_or(date, |seen: Date| seen.min(date)));
latest = Some(latest.map_or(date, |seen: Date| seen.max(date)));
}
assert_eq!(
first,
earliest.unwrap(),
"{name}: the earliest local date is the range's first date"
);
assert_eq!(
last,
latest.unwrap(),
"{name}: the latest local date is the range's last date"
);
}
}
#[test]
fn a_slice_at_the_range_floor_crossing_a_transition_stays_exact_and_agrees() {
use crate::time::{
RuleZone, WallEnd, WallRange, Weekday, Weekdays, WeeklyKey, WindowSpec, ZoneSchedule,
};
let db = TimeZoneDatabase::bundled().unwrap();
let zone = db.zone("Africa/Bissau").unwrap();
let from = Instant::MIN;
let until = Instant::from_minutes(from.minutes() + 3 * 1440).unwrap();
let transitions = zone.transition_instants(from, until).unwrap();
assert_eq!(
transitions.len(),
1,
"Bissau changes offset once, an hour above the floor"
);
let (first, last) = dates_covering(&zone, from, until, &transitions);
let mut earliest = None;
let mut latest = None;
for minute in from.minutes()..until.minutes() {
let date = zone.zoned(Instant::from_minutes(minute).unwrap()).date();
earliest = Some(earliest.map_or(date, |seen: Date| seen.min(date)));
latest = Some(latest.map_or(date, |seen: Date| seen.max(date)));
}
assert_eq!(first, earliest.unwrap(), "earliest local date");
assert_eq!(last, latest.unwrap(), "latest local date");
let spec = WindowSpec::new(
RuleZone::Event,
vec![
WeeklyKey::new(
Weekdays::list([Weekday::Tuesday]),
vec![
WallRange::new(
TimeOfDay::new(22, 0).unwrap(),
WallEnd::Time(TimeOfDay::new(2, 0).unwrap()),
)
.unwrap(),
],
)
.unwrap(),
],
Vec::new(),
)
.unwrap();
let schedule = ZoneSchedule::fixed(zone.clone());
let built = spec.intervals(&schedule, from, until).unwrap();
assert!(
!built.spans().is_empty(),
"the window is live over this slice, so the agreement check below \
is not vacuous"
);
for minute in from.minutes()..until.minutes() {
let instant = Instant::from_minutes(minute).unwrap();
assert_eq!(
built.contains_minute(minute),
spec.contains(instant, &schedule),
"built set and membership disagree at minute {minute}"
);
}
}
}