use std::fmt;
use jiff::civil::Date;
use jiff::{Timestamp, ToSpan};
use crate::error::Rejection;
use crate::reason::RejectionReason as R;
use crate::types::{IspDuration, TimeZoneName};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct IspSpan {
start: u32,
duration: u32,
}
impl IspSpan {
pub fn new(start: u32, duration: u32) -> Result<Self, Rejection> {
if start == 0 {
return Err(Rejection::schema(
"[UFTP §4.2.1]",
"Start 0 is not an ISP: the first ISP of a day is 1.",
));
}
if duration == 0 {
return Err(Rejection::schema(
"[UFTP §4.2.1]",
format!(
"ISP {start} with Duration 0 covers nothing: an ISP element covers at least 1 ISP."
),
));
}
if start.checked_add(duration - 1).is_none() {
return Err(Rejection::schema(
"[UFTP §4.2.1]",
format!(
"ISP {start} with Duration {duration} would end past ISP {}; no day has that many.",
u32::MAX
),
));
}
Ok(Self { start, duration })
}
pub fn single(n: u32) -> Result<Self, Rejection> {
Self::new(n, 1)
}
#[must_use]
pub fn start(&self) -> u32 {
self.start
}
#[must_use]
pub fn duration(&self) -> u32 {
self.duration
}
#[must_use]
pub fn end(&self) -> u32 {
self.start + (self.duration - 1)
}
}
impl fmt::Display for IspSpan {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.duration == 1 {
write!(f, "ISP {}", self.start)
} else {
write!(f, "ISPs {}–{}", self.start, self.end())
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DayGrid {
period: Date,
zone: TimeZoneName,
isp: IspDuration,
start: Timestamp,
count: u32,
}
impl DayGrid {
pub fn new(period: Date, zone: TimeZoneName, isp: IspDuration) -> Result<Self, Rejection> {
let tz = zone.zone().clone();
let start = period
.to_zoned_datetime(tz.clone())
.and_then(|z| z.start_of_day())
.map_err(|e| {
Rejection::rule(
R::PeriodOutOfBounds,
"[UFTP §4.2.2 Period]",
format!("{period} has no start in {zone}: {e}."),
)
})?
.timestamp();
let next = period
.tomorrow()
.and_then(|d| d.to_zoned_datetime(tz))
.and_then(|z| z.start_of_day())
.map_err(|e| {
Rejection::rule(
R::PeriodOutOfBounds,
"[UFTP §4.2.2 Period]",
format!("{period} has no end in {zone}: {e}."),
)
})?
.timestamp();
let seconds = next.as_second() - start.as_second();
let isp_seconds = i64::from(isp.minutes()) * 60;
if seconds <= 0 || seconds % isp_seconds != 0 {
return Err(Rejection::rule(
R::IspDurationRejected,
"[UFTP §4.2.2 ISP-Duration]",
format!(
"{period} in {zone} lasts {seconds} s, which is not a whole number of {isp} ISPs."
),
));
}
let count = u32::try_from(seconds / isp_seconds).map_err(|_| {
Rejection::rule(
R::IspDurationRejected,
"[UFTP §4.2.2 ISP-Duration]",
format!("{period} in {zone} has more {isp} ISPs than can be numbered."),
)
})?;
Ok(Self {
period,
zone,
isp,
start,
count,
})
}
#[must_use]
pub fn period(&self) -> Date {
self.period
}
#[must_use]
pub fn zone(&self) -> &TimeZoneName {
&self.zone
}
#[must_use]
pub fn isp_duration(&self) -> IspDuration {
self.isp
}
#[must_use]
pub fn count(&self) -> u32 {
self.count
}
pub fn interval(&self, n: u32) -> Result<(Timestamp, Timestamp), Rejection> {
if n == 0 || n > self.count {
return Err(Rejection::rule(
R::IspsOutOfBounds,
"[UFTP §4.2.1]",
format!("ISP {n} is not in {} ({} ISPs).", self.period, self.count),
));
}
let minutes = i64::from(self.isp.minutes());
let begin = self
.start
.checked_add((i64::from(n - 1) * minutes).minutes())
.map_err(|_| self.beyond_time(n))?;
let end = begin
.checked_add(minutes.minutes())
.map_err(|_| self.beyond_time(n))?;
Ok((begin, end))
}
fn beyond_time(&self, n: u32) -> Rejection {
Rejection::rule(
R::IspsOutOfBounds,
"[UFTP §4.2.1]",
format!(
"ISP {n} of {} in {} lies outside the time range this library represents.",
self.period, self.zone
),
)
}
#[must_use]
pub fn isp_at(&self, t: Timestamp) -> Option<u32> {
let offset = t.as_second() - self.start.as_second();
if offset < 0 {
return None;
}
let n = u32::try_from(offset / (i64::from(self.isp.minutes()) * 60)).ok()? + 1;
(n <= self.count).then_some(n)
}
pub fn check(&self, spans: &[IspSpan]) -> Result<(), Rejection> {
let mut sorted: Vec<(usize, IspSpan)> = spans.iter().copied().enumerate().collect();
sorted.sort_by_key(|&(_, s)| s);
for &(i, s) in &sorted {
if s.end() > self.count {
return Err(Rejection::rule(
R::IspsOutOfBounds,
"[UFTP §4.2.1] ISP elements may not cross period boundaries",
format!(
"{s} crosses the end of {} ({} ISPs).",
self.period, self.count
),
)
.at(format!("ISP[{}]", i + 1)));
}
}
for pair in sorted.windows(2) {
let ((_, a), (j, b)) = (pair[0], pair[1]);
if b.start() <= a.end() {
return Err(Rejection::rule(
R::IspConflict,
"[UFTP §4.2.1] each ISP in a period may only be addressed once",
format!("ISP {} is addressed twice ({a} and {b}).", b.start()),
)
.at(format!("ISP[{}]", j + 1)));
}
}
Ok(())
}
}