use core::fmt;
use jiff::Timestamp;
use crate::time::civil::{Date, TimeOfDay};
use crate::time::error::TimeError;
const MIN_UNIX_SECONDS: i64 = 157_766_400;
const MAX_UNIX_SECONDS: i64 = 4_102_444_800;
const MIN_UNIX_MINUTES: i64 = MIN_UNIX_SECONDS / 60;
const MAX_UNIX_MINUTES: i64 = MAX_UNIX_SECONDS / 60;
const NANOS_PER_SECOND: u32 = 1_000_000_000;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Instant {
minutes: i64,
}
impl Instant {
pub const MIN: Self = Self {
minutes: MIN_UNIX_MINUTES,
};
pub const MAX: Self = Self {
minutes: MAX_UNIX_MINUTES,
};
pub fn from_minutes(minutes: i64) -> Result<Self, TimeError> {
if !(MIN_UNIX_MINUTES..=MAX_UNIX_MINUTES).contains(&minutes) {
return Err(TimeError::InstantOutOfRange {
seconds: minutes.saturating_mul(60),
});
}
Ok(Self { minutes })
}
pub fn from_unix_seconds(seconds: i64) -> Result<Self, TimeError> {
check_range(seconds)?;
if seconds % 60 != 0 {
return Err(TimeError::InstantNotAligned { seconds });
}
Ok(Self {
minutes: seconds / 60,
})
}
pub fn floor_to_minute(seconds: i64) -> Result<Self, TimeError> {
check_range(seconds)?;
Ok(Self {
minutes: seconds.div_euclid(60),
})
}
pub fn ceil_to_minute(seconds: i64) -> Result<Self, TimeError> {
check_range(seconds)?;
Ok(Self {
minutes: seconds.div_euclid(60) + i64::from(seconds.rem_euclid(60) != 0),
})
}
pub fn from_unix_seconds_nanos(seconds: i64, nanos: u32) -> Result<Self, TimeError> {
check_nanos(nanos)?;
check_range(seconds)?;
if seconds.rem_euclid(60) != 0 || nanos != 0 {
return Err(TimeError::InstantNotAligned { seconds });
}
Ok(Self {
minutes: seconds.div_euclid(60),
})
}
pub fn floor_to_minute_nanos(seconds: i64, nanos: u32) -> Result<Self, TimeError> {
check_nanos(nanos)?;
check_range(seconds)?;
Ok(Self {
minutes: seconds.div_euclid(60),
})
}
pub fn ceil_to_minute_nanos(seconds: i64, nanos: u32) -> Result<Self, TimeError> {
check_nanos(nanos)?;
check_range(seconds)?;
let stray = seconds.rem_euclid(60) != 0 || nanos != 0;
let minutes = seconds.div_euclid(60) + i64::from(stray);
if !(MIN_UNIX_MINUTES..=MAX_UNIX_MINUTES).contains(&minutes) {
return Err(TimeError::InstantOutOfRange {
seconds: minutes.saturating_mul(60),
});
}
Ok(Self { minutes })
}
pub fn from_utc(date: Date, time: TimeOfDay) -> Result<Self, TimeError> {
let unrepresentable = || TimeError::CivilToInstant { date, time };
let seconds = jiff::tz::Offset::UTC
.to_timestamp(time.on(date))
.map(Timestamp::as_second)
.map_err(|_| unrepresentable())?;
Self::from_unix_seconds(seconds).map_err(|err| match err {
TimeError::InstantOutOfRange { .. } => unrepresentable(),
other => other,
})
}
#[must_use]
pub const fn minutes(&self) -> i64 {
self.minutes
}
#[must_use]
pub fn checked_add(self, d: Duration) -> Option<Self> {
self.minutes
.checked_add(d.minutes())
.and_then(|minutes| Self::from_minutes(minutes).ok())
}
#[must_use]
pub fn checked_sub(self, d: Duration) -> Option<Self> {
self.minutes
.checked_sub(d.minutes())
.and_then(|minutes| Self::from_minutes(minutes).ok())
}
#[must_use]
pub const fn unix_seconds(&self) -> i64 {
self.minutes * 60
}
pub(crate) fn as_jiff(self) -> Timestamp {
Timestamp::from_second(self.unix_seconds())
.expect("a supported instant lies inside jiff's timestamp range")
}
}
fn check_nanos(nanos: u32) -> Result<(), TimeError> {
if nanos < NANOS_PER_SECOND {
Ok(())
} else {
Err(TimeError::NanosOutOfRange { nanos })
}
}
fn check_range(seconds: i64) -> Result<(), TimeError> {
if (MIN_UNIX_SECONDS..=MAX_UNIX_SECONDS).contains(&seconds) {
Ok(())
} else {
Err(TimeError::InstantOutOfRange { seconds })
}
}
impl fmt::Debug for Instant {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for Instant {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let ts = self.as_jiff();
let dt = jiff::tz::Offset::UTC.to_datetime(ts);
write!(
f,
"{:04}-{:02}-{:02}T{:02}:{:02}Z",
dt.year(),
dt.month(),
dt.day(),
dt.hour(),
dt.minute(),
)
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Duration {
minutes: i64,
}
impl Duration {
pub const ZERO: Self = Self { minutes: 0 };
#[must_use]
pub const fn from_minutes(minutes: u32) -> Self {
Self {
minutes: minutes as i64,
}
}
#[must_use]
pub const fn from_hours_minutes(hours: u32, minutes: u32) -> Self {
Self {
minutes: hours as i64 * 60 + minutes as i64,
}
}
#[must_use]
pub const fn from_hours(hours: u32) -> Self {
Self {
minutes: hours as i64 * 60,
}
}
pub fn from_parts(days: u32, hours: u32, minutes: u32) -> Result<Self, TimeError> {
if days != 0 {
return Err(TimeError::DurationHasDays { days });
}
Ok(Self::from_hours_minutes(hours, minutes))
}
#[must_use]
pub const fn minutes(&self) -> i64 {
self.minutes
}
}
impl Default for Duration {
fn default() -> Self {
Self::ZERO
}
}
impl fmt::Debug for Duration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for Duration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.minutes % 60 == 0 {
write!(f, "{}h", self.minutes / 60)
} else {
write!(f, "{}m", self.minutes)
}
}
}
#[cfg(test)]
mod tests {
use super::{Duration, Instant, MAX_UNIX_SECONDS, MIN_UNIX_SECONDS};
use crate::time::{Date, TimeError, TimeOfDay};
#[test]
fn a_utc_civil_time_names_exactly_one_instant() {
assert_eq!(
Instant::from_utc(
Date::new(2027, 3, 9).unwrap(),
TimeOfDay::new(15, 0).unwrap()
)
.unwrap()
.to_string(),
"2027-03-09T15:00Z"
);
assert_eq!(
Instant::from_utc(Date::new(1975, 1, 1).unwrap(), TimeOfDay::MIDNIGHT),
Ok(Instant::MIN)
);
assert_eq!(
Instant::from_utc(Date::new(2100, 1, 1).unwrap(), TimeOfDay::MIDNIGHT),
Ok(Instant::MAX)
);
let before = Date::new(1974, 12, 31).unwrap();
assert_eq!(
Instant::from_utc(before, TimeOfDay::MIDNIGHT),
Err(TimeError::CivilToInstant {
date: before,
time: TimeOfDay::MIDNIGHT,
})
);
}
#[test]
fn checked_arithmetic_stops_at_the_supported_range() {
let later = Instant::MIN.checked_add(Duration::from_hours(1)).unwrap();
assert_eq!(later.minutes() - Instant::MIN.minutes(), 60);
assert_eq!(
later.checked_sub(Duration::from_hours(1)),
Some(Instant::MIN)
);
assert_eq!(Instant::MAX.checked_add(Duration::from_minutes(1)), None);
assert_eq!(Instant::MIN.checked_sub(Duration::from_minutes(1)), None);
assert_eq!(Instant::MIN.checked_add(Duration::ZERO), Some(Instant::MIN));
}
#[test]
fn the_supported_range_is_the_specified_one() {
assert_eq!(Instant::MIN.to_string(), "1975-01-01T00:00Z");
assert_eq!(Instant::MAX.to_string(), "2100-01-01T00:00Z");
assert_eq!(Instant::MIN.unix_seconds(), MIN_UNIX_SECONDS);
assert_eq!(Instant::MAX.unix_seconds(), MAX_UNIX_SECONDS);
assert!(Instant::from_unix_seconds(MIN_UNIX_SECONDS).is_ok());
assert!(Instant::from_unix_seconds(MAX_UNIX_SECONDS).is_ok());
assert_eq!(
Instant::from_unix_seconds(MIN_UNIX_SECONDS - 60),
Err(TimeError::InstantOutOfRange {
seconds: MIN_UNIX_SECONDS - 60
})
);
assert_eq!(
Instant::from_unix_seconds(MAX_UNIX_SECONDS + 60),
Err(TimeError::InstantOutOfRange {
seconds: MAX_UNIX_SECONDS + 60
})
);
assert_eq!(
TimeError::InstantOutOfRange { seconds: 0 }.code(),
"instant_out_of_range"
);
}
#[test]
fn rounding_moves_in_the_direction_the_request_needs() {
let seconds = 1_804_604_430;
assert_eq!(
Instant::floor_to_minute(seconds).unwrap().to_string(),
"2027-03-09T15:00Z"
);
assert_eq!(
Instant::ceil_to_minute(seconds).unwrap().to_string(),
"2027-03-09T15:01Z"
);
for aligned in [1_804_604_400, 1_804_604_460] {
assert_eq!(
Instant::floor_to_minute(aligned).unwrap(),
Instant::ceil_to_minute(aligned).unwrap()
);
}
}
#[test]
fn unaligned_instants_are_rejected() {
assert_eq!(
Instant::from_unix_seconds(1_804_604_401),
Err(TimeError::InstantNotAligned {
seconds: 1_804_604_401
})
);
assert_eq!(
TimeError::InstantNotAligned { seconds: 1 }.code(),
"instant_not_aligned"
);
assert_eq!(Instant::MIN.minutes() * 60, Instant::MIN.unix_seconds());
}
#[test]
fn durations_are_exact_minutes() {
assert_eq!(Duration::from_hours_minutes(1, 30).minutes(), 90);
assert_eq!(Duration::from_minutes(45).minutes(), 45);
assert_eq!(Duration::from_parts(0, 1, 30).unwrap().minutes(), 90);
assert_eq!(
Duration::from_parts(1, 0, 0),
Err(TimeError::DurationHasDays { days: 1 })
);
assert_eq!(
TimeError::DurationHasDays { days: 1 }.code(),
"duration_has_days"
);
assert_eq!(Duration::from_hours_minutes(1, 30).to_string(), "90m");
assert_eq!(Duration::from_hours_minutes(2, 0).to_string(), "2h");
}
}