use crate::intervals::IntervalSet;
use crate::time::breakpoints::{self, BreakpointSource};
use crate::time::error::{BlackoutError, TimeError};
use crate::time::window::RuleZone;
use crate::time::{Instant, LocalDateTime, Zone, ZoneSchedule};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BlackoutSpan {
start: LocalDateTime,
end: LocalDateTime,
}
impl BlackoutSpan {
pub fn new(start: LocalDateTime, end: LocalDateTime) -> Result<Self, BlackoutError> {
if end <= start {
return Err(BlackoutError::SpanEmpty { start, end });
}
Ok(Self { start, end })
}
#[must_use]
pub const fn start(&self) -> LocalDateTime {
self.start
}
#[must_use]
pub const fn end(&self) -> LocalDateTime {
self.end
}
fn contains(&self, at: LocalDateTime) -> bool {
self.start <= at && at < self.end
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BlackoutSpec {
zone: RuleZone,
spans: Vec<BlackoutSpan>,
}
impl BlackoutSpec {
#[must_use]
pub fn new(zone: RuleZone, spans: Vec<BlackoutSpan>) -> Self {
let mut spans = spans;
spans.sort_unstable();
let mut merged: Vec<BlackoutSpan> = Vec::with_capacity(spans.len());
for span in spans {
match merged.last_mut() {
Some(last) if span.start <= last.end => {
last.end = last.end.max(span.end);
}
_ => merged.push(span),
}
}
Self {
zone,
spans: merged,
}
}
#[must_use]
pub fn contains(&self, instant: Instant, zones: &ZoneSchedule) -> bool {
self.member(instant, zones.zone_at(instant))
}
pub fn intervals(
&self,
zones: &ZoneSchedule,
from: Instant,
until: Instant,
) -> Result<IntervalSet, TimeError> {
breakpoints::build(self, zones, from, until)
}
#[must_use]
pub fn zone(&self) -> &RuleZone {
&self.zone
}
#[must_use]
pub fn spans(&self) -> &[BlackoutSpan] {
&self.spans
}
fn local(instant: Instant, zone: &Zone) -> LocalDateTime {
let zoned = instant.zoned(zone);
LocalDateTime::new(zoned.date(), zoned.time())
}
}
impl BreakpointSource for BlackoutSpec {
fn member(&self, instant: Instant, zone: &Zone) -> bool {
let local = Self::local(instant, zone);
let index = self.spans.partition_point(|span| span.start <= local);
index > 0 && self.spans[index - 1].contains(local)
}
fn breakpoints(
&self,
zone: &Zone,
start: Instant,
end: Instant,
) -> Result<Vec<Instant>, TimeError> {
let transitions = zone.transition_instants(start, end)?;
let (first, last) = breakpoints::dates_covering(zone, start, end, &transitions);
let mut instants = Vec::new();
debug_assert!(self
.spans
.windows(2)
.all(|pair| pair[0].end < pair[1].start
&& pair[0].end.date() <= pair[1].end.date()));
let first_index = self.spans.partition_point(|span| span.end.date() < first);
for span in &self.spans[first_index..] {
if span.start.date() > last {
break;
}
if (first..=last).contains(&span.start.date()) {
breakpoints::push_local(&mut instants, zone, span.start.date(), span.start.time())?;
}
if (first..=last).contains(&span.end.date()) {
breakpoints::push_local(&mut instants, zone, span.end.date(), span.end.time())?;
}
}
instants.extend(transitions);
Ok(instants)
}
}
#[cfg(test)]
mod tests {
use super::{BlackoutSpan, BlackoutSpec};
use crate::time::window::RuleZone;
use crate::time::{
BlackoutError, Date, Instant, LocalDateTime, LocalResolution, TimeOfDay, Zone, ZoneName,
ZoneSchedule,
};
fn utc(year: i16, month: i8, day: i8, hour: u8, minute: u8) -> Instant {
let date = Date::new(year, month, day).unwrap();
let time = TimeOfDay::new(hour, minute).unwrap();
let LocalResolution::Unique(instant) = Zone::utc().resolve_local(date, time).unwrap()
else {
panic!("UTC has no transitions")
};
instant
}
fn at(day: i8, hour: u8, minute: u8) -> LocalDateTime {
LocalDateTime::new(
Date::new(2027, 3, day).unwrap(),
TimeOfDay::new(hour, minute).unwrap(),
)
}
fn span(start: (i8, u8, u8), end: (i8, u8, u8)) -> BlackoutSpan {
BlackoutSpan::new(at(start.0, start.1, start.2), at(end.0, end.1, end.2)).unwrap()
}
fn spec(spans: Vec<BlackoutSpan>) -> BlackoutSpec {
BlackoutSpec::new(RuleZone::Named(ZoneName::new("UTC").unwrap()), spans)
}
fn built(spec: &BlackoutSpec, from: Instant, until: Instant) -> Vec<(i64, i64)> {
spec.intervals(&ZoneSchedule::fixed(Zone::utc()), from, until)
.unwrap()
.spans()
.iter()
.map(|span| (span.start(), span.end()))
.collect()
}
#[test]
fn an_inverted_or_zero_length_span_is_rejected() {
for (start, end) in [
((10, 12, 0), (10, 12, 0)),
((10, 12, 0), (10, 9, 0)),
((11, 0, 0), (10, 0, 0)),
] {
let error = BlackoutSpan::new(at(start.0, start.1, start.2), at(end.0, end.1, end.2))
.unwrap_err();
assert_eq!(
error,
BlackoutError::SpanEmpty {
start: at(start.0, start.1, start.2),
end: at(end.0, end.1, end.2),
}
);
assert_eq!(error.code(), "blackout_span_empty");
}
assert!(BlackoutSpan::new(at(10, 0, 0), at(10, 0, 1)).is_ok());
}
#[test]
fn a_span_is_half_open() {
let spec = spec(vec![span((10, 9, 0), (10, 17, 0))]);
let zones = ZoneSchedule::fixed(Zone::utc());
assert!(!spec.contains(utc(2027, 3, 10, 8, 59), &zones));
assert!(spec.contains(utc(2027, 3, 10, 9, 0), &zones));
assert!(spec.contains(utc(2027, 3, 10, 16, 59), &zones));
assert!(!spec.contains(utc(2027, 3, 10, 17, 0), &zones));
}
#[test]
fn overlapping_and_touching_spans_coalesce() {
let spec = spec(vec![
span((10, 12, 0), (10, 14, 0)),
span((10, 9, 0), (10, 11, 0)),
span((10, 11, 0), (10, 13, 0)),
]);
assert_eq!(
built(&spec, utc(2027, 3, 10, 0, 0), utc(2027, 3, 11, 0, 0)),
[(
utc(2027, 3, 10, 9, 0).minutes(),
utc(2027, 3, 10, 14, 0).minutes()
)]
);
assert_eq!(spec.spans().len(), 1);
assert_eq!(
(spec.spans()[0].start(), spec.spans()[0].end()),
(at(10, 9, 0), at(10, 14, 0))
);
}
#[test]
fn a_blackout_spanning_midnight_is_one_span() {
let spec = spec(vec![span((10, 22, 0), (11, 3, 0))]);
assert_eq!(
built(&spec, utc(2027, 3, 10, 0, 0), utc(2027, 3, 12, 0, 0)),
[(
utc(2027, 3, 10, 22, 0).minutes(),
utc(2027, 3, 11, 3, 0).minutes()
)]
);
}
#[test]
fn a_blackout_builds_over_the_requested_range_without_clipping_to_midnight() {
let spec = spec(vec![span((10, 9, 0), (10, 17, 0))]);
assert_eq!(
built(&spec, utc(2027, 3, 10, 10, 30), utc(2027, 3, 10, 12, 30)),
[(
utc(2027, 3, 10, 10, 30).minutes(),
utc(2027, 3, 10, 12, 30).minutes()
)]
);
}
#[test]
fn the_interval_set_agrees_with_instant_membership_minute_by_minute() {
let spec = spec(vec![
span((9, 18, 0), (10, 6, 30)),
span((10, 12, 0), (10, 14, 0)),
span((11, 0, 0), (12, 0, 0)),
]);
let zones = ZoneSchedule::fixed(Zone::utc());
let from = utc(2027, 3, 9, 0, 0);
let until = utc(2027, 3, 12, 0, 0);
let intervals = spec.intervals(&zones, from, until).unwrap();
for minute in from.minutes()..until.minutes() {
let instant = Instant::from_minutes(minute).unwrap();
assert_eq!(
intervals.contains_minute(minute),
spec.contains(instant, &zones),
"{instant}: the breakpoint builder and instant membership disagree"
);
}
}
}