use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::RangeInclusive;
use jiff::civil::{Date, Time};
use jiff::tz::{AmbiguousOffset, Offset, TimeZone};
use jiff::{SignedDuration, Timestamp};
use crate::Error;
pub const MAX_ISPS: u32 = 527_040;
const NANOS_PER_MINUTE: i128 = 60_000_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct IspDuration(u16);
impl IspDuration {
pub const FIFTEEN_MINUTES: IspDuration = IspDuration(15);
pub fn from_minutes(minutes: u16) -> Result<IspDuration, Error> {
if minutes == 0 || 1440 % minutes != 0 {
return Err(Error::IspDuration { minutes });
}
Ok(IspDuration(minutes))
}
#[must_use]
pub const fn minutes(self) -> u16 {
self.0
}
fn nanos(self) -> i128 {
i128::from(self.0) * NANOS_PER_MINUTE
}
}
impl IspDuration {
pub(crate) fn from_canonical(text: &str) -> Option<IspDuration> {
let minutes = text.strip_prefix("PT")?.strip_suffix('M')?;
if minutes.starts_with('0') || !minutes.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
IspDuration::from_minutes(minutes.parse().ok()?).ok()
}
}
impl fmt::Display for IspDuration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "PT{}M", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Window {
from: Timestamp,
until: Timestamp,
}
impl Window {
pub fn new(from: Timestamp, until: Timestamp) -> Result<Window, Error> {
if until <= from {
return Err(Error::EmptyWindow { from, until });
}
Ok(Window { from, until })
}
#[must_use]
pub fn from(self) -> Timestamp {
self.from
}
#[must_use]
pub fn until(self) -> Timestamp {
self.until
}
}
impl fmt::Display for Window {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} to {}", self.from, self.until)
}
}
#[derive(Debug, Clone)]
pub struct Grid {
start: Timestamp,
isp: IspDuration,
count: u32,
first: u32,
zone: TimeZone,
}
impl PartialEq for Grid {
fn eq(&self, other: &Grid) -> bool {
self.start == other.start
&& self.isp == other.isp
&& self.count == other.count
&& self.first == other.first
}
}
impl Eq for Grid {}
impl Hash for Grid {
fn hash<H: Hasher>(&self, state: &mut H) {
self.start.hash(state);
self.isp.hash(state);
self.count.hash(state);
self.first.hash(state);
}
}
impl Grid {
pub fn new(
start: Timestamp,
isp: IspDuration,
count: u32,
zone: TimeZone,
) -> Result<Grid, Error> {
if count == 0 || count > MAX_ISPS {
return Err(Error::GridSize {
count: u64::from(count),
});
}
let grid = Grid {
start,
isp,
count,
first: 1,
zone,
};
grid.offset(count)
.ok_or(Error::TimeRange { start, count })?;
Ok(grid)
}
pub fn day(date: Date, zone: &TimeZone, isp: IspDuration) -> Result<Grid, Error> {
let day_error = |reason| Error::Day {
date,
zone: zone_name(zone),
reason,
};
let start_of = |d: Date| {
d.to_zoned_datetime(zone.clone())
.and_then(|z| z.start_of_day())
.map(|z| z.timestamp())
};
let start = start_of(date).map_err(|_| day_error("the day has no start"))?;
let next = date
.tomorrow()
.and_then(start_of)
.map_err(|_| day_error("the next day has no start"))?;
let length = next.as_nanosecond() - start.as_nanosecond();
if length <= 0 || length % isp.nanos() != 0 {
return Err(day_error("the day is not a whole number of ISPs"));
}
let count = u32::try_from(length / isp.nanos())
.map_err(|_| day_error("the day has too many ISPs"))?;
Grid::new(start, isp, count, zone.clone())
}
pub fn slice(&self, isps: RangeInclusive<u32>) -> Result<Grid, Error> {
let (first, last) = (*isps.start(), *isps.end());
let refuse = || Error::IspRange {
first,
last,
count: self.count,
};
let (Some(from), Some(_)) = (self.index(first), self.index(last)) else {
return Err(refuse());
};
if last < first {
return Err(refuse());
}
let start = self.offset(from).ok_or_else(refuse)?;
let mut grid = Grid::new(start, self.isp, last - first + 1, self.zone.clone())?;
grid.first = first;
Ok(grid)
}
pub(crate) fn numbered(
start: Timestamp,
isp: IspDuration,
count: u32,
first: u32,
zone: TimeZone,
) -> Result<Grid, Error> {
if count == 0 {
return Err(Error::GridSize { count: 0 });
}
if first == 0
|| first
.checked_add(count - 1)
.is_none_or(|last| last > MAX_ISPS)
{
return Err(Error::IspRange {
first,
last: first.saturating_add(count.saturating_sub(1)),
count: MAX_ISPS,
});
}
let mut grid = Grid::new(start, isp, count, zone)?;
grid.first = first;
Ok(grid)
}
#[must_use]
pub fn first(&self) -> u32 {
self.first
}
#[must_use]
pub fn numbers(&self) -> RangeInclusive<u32> {
self.first..=self.first.saturating_add(self.count - 1)
}
pub(crate) fn index(&self, isp: u32) -> Option<u32> {
isp.checked_sub(self.first).filter(|&i| i < self.count)
}
#[must_use]
pub fn with_zone(mut self, zone: TimeZone) -> Grid {
self.zone = zone;
self
}
#[must_use]
pub fn zone(&self) -> &TimeZone {
&self.zone
}
#[must_use]
pub fn start(&self) -> Timestamp {
self.start
}
#[must_use]
pub fn end(&self) -> Timestamp {
self.offset(self.count).unwrap_or(self.start)
}
#[must_use]
pub fn isp(&self) -> IspDuration {
self.isp
}
#[must_use]
pub fn count(&self) -> u32 {
self.count
}
#[must_use]
pub fn date(&self) -> Date {
self.zone.to_datetime(self.start).date()
}
#[must_use]
pub fn interval(&self, isp: u32) -> Option<Window> {
let i = self.index(isp)?;
Some(Window {
from: self.offset(i)?,
until: self.offset(i + 1)?,
})
}
#[must_use]
pub fn label(&self, isp: u32) -> Option<IspLabel> {
let w = self.interval(isp)?;
Some(IspLabel {
isp,
from: w.from,
until: w.until,
offset: self.zone.to_offset(w.from),
})
}
pub(crate) fn label_total(&self, isp: u32) -> IspLabel {
self.label(isp).unwrap_or(IspLabel {
isp,
from: self.start,
until: self.start,
offset: self.zone.to_offset(self.start),
})
}
#[must_use]
pub fn isp_at(&self, t: Timestamp) -> Option<u32> {
let since = t.as_nanosecond() - self.start.as_nanosecond();
if since < 0 {
return None;
}
let index = u32::try_from(since / self.isp.nanos()).ok()?;
(index < self.count).then_some(self.first + index)
}
#[must_use]
pub fn isps(&self, window: Window) -> Option<RangeInclusive<u32>> {
if window.until <= self.start || window.from >= self.end() {
return None;
}
let first = self.isp_at(window.from.max(self.start))?;
let last_instant = window
.until
.min(self.end())
.checked_sub(SignedDuration::from_nanos(1));
let last = self.isp_at(last_instant.ok()?)?;
Some(first..=last)
}
pub fn local(&self, time: Time) -> Result<Timestamp, Error> {
self.local_on(self.date(), time)
}
pub fn window(&self, from: Time, until: Time) -> Result<Window, Error> {
let date = self.date();
let start = self.local_on(date, from)?;
let end_date = if until <= from {
date.tomorrow().map_err(|_| Error::Day {
date,
zone: zone_name(&self.zone),
reason: "the next day does not exist",
})?
} else {
date
};
let end = self.local_on(end_date, until)?;
Window::new(start, end)
}
fn local_on(&self, date: Date, time: Time) -> Result<Timestamp, Error> {
let refuse = |reason| Error::LocalTime {
date,
time,
zone: zone_name(&self.zone),
reason,
};
let ambiguous = self.zone.to_ambiguous_timestamp(date.to_datetime(time));
match ambiguous.offset() {
AmbiguousOffset::Unambiguous { .. } => ambiguous
.unambiguous()
.map_err(|_| refuse("outside the representable range")),
AmbiguousOffset::Gap { .. } => Err(refuse("skipped: the clocks jump over it")),
AmbiguousOffset::Fold { .. } => Err(refuse("ambiguous: the clocks show it twice")),
}
}
fn offset(&self, isps: u32) -> Option<Timestamp> {
let nanos = i128::from(isps) * self.isp.nanos();
let nanos = i64::try_from(nanos).ok()?;
self.start
.checked_add(SignedDuration::from_nanos(nanos))
.ok()
}
}
pub(crate) fn zone_name(zone: &TimeZone) -> String {
zone.iana_name().unwrap_or("unnamed").to_owned()
}
impl fmt::Display for Grid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.first == 1 {
write!(f, "{} ISPs", self.count)?;
} else {
write!(f, "ISPs {}–{}", self.first, self.first + (self.count - 1))?;
}
write!(
f,
" of {} from {} ({})",
self.isp,
self.start,
zone_name(&self.zone)
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct IspLabel {
isp: u32,
from: Timestamp,
until: Timestamp,
offset: Offset,
}
impl IspLabel {
#[must_use]
pub fn isp(self) -> u32 {
self.isp
}
#[must_use]
pub fn window(self) -> Window {
Window {
from: self.from,
until: self.until,
}
}
}
impl fmt::Display for IspLabel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let from = self.offset.to_datetime(self.from);
let until = self.offset.to_datetime(self.until);
let seconds = self.offset.seconds();
let sign = if seconds < 0 { '-' } else { '+' };
let s = seconds.unsigned_abs();
write!(
f,
"ISP {} ({:02}:{:02}–{:02}:{:02} {sign}{:02}:{:02})",
self.isp,
from.hour(),
from.minute(),
until.hour(),
until.minute(),
s / 3_600,
(s % 3_600) / 60
)
}
}