use std::thread;
use std::time::Duration;
use jiff::{SignedDuration, Timestamp};
pub trait Clock {
fn now(&self) -> Timestamp;
fn wait_until(&mut self, at: Timestamp);
}
#[derive(Clone, Copy, Debug, Default)]
pub struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> Timestamp {
Timestamp::now()
}
fn wait_until(&mut self, at: Timestamp) {
while let Ok(left) = Duration::try_from(at.duration_since(Timestamp::now())) {
if left.is_zero() {
break;
}
thread::sleep(left.min(Duration::from_secs(30)));
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Moment {
At(Timestamp),
Wait(SignedDuration),
}
impl Moment {
pub fn read(text: &str) -> Option<Self> {
let text = text.trim();
if text.starts_with('P') {
duration(text).map(Self::Wait)
} else {
text.parse().ok().map(Self::At)
}
}
pub fn from(self, from: Timestamp) -> Timestamp {
match self {
Self::At(at) => at,
Self::Wait(wait) => from.saturating_add(wait).unwrap_or(Timestamp::MAX),
}
}
}
fn duration(text: &str) -> Option<SignedDuration> {
let rest = text.strip_prefix('P')?;
let (days, time) = match rest.split_once('T') {
Some((days, time)) => (days, Some(time)),
None => (rest, None),
};
let mut seconds: i64 = 0;
for (number, unit) in parts(days)? {
seconds += number.checked_mul(match unit {
'W' => 7 * 86_400,
'D' => 86_400,
_ => return None,
})?;
}
if let Some(time) = time {
for (number, unit) in parts(time)? {
seconds += number.checked_mul(match unit {
'H' => 3_600,
'M' => 60,
'S' => 1,
_ => return None,
})?;
}
}
(seconds > 0).then(|| SignedDuration::from_secs(seconds))
}
fn parts(text: &str) -> Option<Vec<(i64, char)>> {
let mut found = Vec::new();
let mut number = String::new();
for character in text.chars() {
if character.is_ascii_digit() {
number.push(character);
} else {
found.push((number.parse().ok()?, character));
number.clear();
}
}
number.is_empty().then_some(found)
}
pub fn words(at: Timestamp) -> String {
at.to_zoned(jiff::tz::TimeZone::system())
.strftime("%Y-%m-%d %H:%M (%:z)")
.to_string()
}
#[cfg(test)]
mod tests {
use jiff::SignedDuration;
use super::Moment;
#[test]
fn deadlines_are_read_as_dates_or_waits() {
let hours = |hours| Some(Moment::Wait(SignedDuration::from_hours(hours)));
assert_eq!(Moment::read("P7D"), hours(7 * 24));
assert_eq!(Moment::read("P2W"), hours(14 * 24));
assert_eq!(Moment::read("PT48H"), hours(48));
assert_eq!(Moment::read("P1DT12H"), hours(36));
assert_eq!(
Moment::read("PT1H30M45S"),
Some(Moment::Wait(SignedDuration::from_secs(5445)))
);
assert_eq!(
Moment::read("2027-03-20T07:00-03:00"),
Some(Moment::At("2027-03-20T10:00:00Z".parse().expect("a time")))
);
for wrong in [
"P",
"PT",
"P0D",
"P1Y",
"P1M",
"PT1D",
"P1H",
"2027-02-30T10:00Z",
"soon",
] {
assert_eq!(Moment::read(wrong), None, "{wrong}");
}
}
}