vpf-runner 0.4.0

The reference runner of the Verifiable Plan Format (VPF): runs a plan step by step and proves each step.
Documentation
//! Time: the clock a run reads and waits on, and the times a plan writes as deadlines.

use std::thread;
use std::time::Duration;

use jiff::{SignedDuration, Timestamp};

/// The clock a run reads, and waits on until a step's time comes.
pub trait Clock {
    /// Now.
    fn now(&self) -> Timestamp;

    /// Waits until `at`.
    fn wait_until(&mut self, at: Timestamp);
}

/// The computer's own clock.
#[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)));
        }
    }
}

/// A time as a plan writes it: a date and time, or a wait from some moment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Moment {
    /// A date and time.
    At(Timestamp),
    /// A wait.
    Wait(SignedDuration),
}

impl Moment {
    /// Reads a deadline: a date and time with its offset, or a duration in weeks, or days and a time.
    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)
        }
    }

    /// When it is, a wait counted from `from`.
    pub fn from(self, from: Timestamp) -> Timestamp {
        match self {
            Self::At(at) => at,
            Self::Wait(wait) => from.saturating_add(wait).unwrap_or(Timestamp::MAX),
        }
    }
}

/// `P2W`, or `P` with days and a time such as `P1DT12H`, `PT30M` or `PT45S`.
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))
}

/// `12H30M` as `[(12, 'H'), (30, 'M')]`.
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)
}

/// A time as the person reads it, where the runner runs.
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}");
        }
    }
}