uftp 0.2.0

UFTP 3.1, the USEF Flex Trading Protocol (LF Energy Shapeshifter), in Rust: all 26 messages, CS1 signing and a receive pipeline for DSOs and aggregators.
Documentation
//! Imbalance settlement periods (ISPs): numbering, instants and the two rules every ISP
//! list obeys `[UFTP §4.2.1]`. Each ISP in a period is addressed at most once, and no ISP
//! element crosses the period's boundary.

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};

/// One ISP element: `Start` (the first ISP of the day is 1) and `Duration` (a number of
/// ISPs, 1 by default).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct IspSpan {
    start: u32,
    duration: u32,
}

impl IspSpan {
    /// A span of `duration` ISPs starting at `start`.
    ///
    /// # Errors
    /// If `start` or `duration` is zero, or the span overflows.
    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 })
    }

    /// One ISP.
    ///
    /// # Errors
    /// If `n` is zero.
    pub fn single(n: u32) -> Result<Self, Rejection> {
        Self::new(n, 1)
    }

    /// The first ISP.
    #[must_use]
    pub fn start(&self) -> u32 {
        self.start
    }

    /// The number of ISPs.
    #[must_use]
    pub fn duration(&self) -> u32 {
        self.duration
    }

    /// The last ISP, inclusive.
    #[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())
        }
    }
}

/// The ISPs of one day (a `Period`) in one time zone.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DayGrid {
    period: Date,
    zone: TimeZoneName,
    isp: IspDuration,
    start: Timestamp,
    count: u32,
}

impl DayGrid {
    /// The grid of `period` in `zone` with ISPs of `isp`. On DST change days the grid has
    /// fewer or more ISPs: 92 or 100 quarter-hours in Central Europe.
    ///
    /// # Errors
    /// If the day's length in the zone is not a whole number of ISPs, as with a 30-minute
    /// DST shift and one-hour ISPs.
    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,
        })
    }

    /// The day.
    #[must_use]
    pub fn period(&self) -> Date {
        self.period
    }

    /// The time zone.
    #[must_use]
    pub fn zone(&self) -> &TimeZoneName {
        &self.zone
    }

    /// The ISP length.
    #[must_use]
    pub fn isp_duration(&self) -> IspDuration {
        self.isp
    }

    /// How many ISPs the day has.
    #[must_use]
    pub fn count(&self) -> u32 {
        self.count
    }

    /// The half-open interval `[start, end)` of ISP `n`.
    ///
    /// # Errors
    /// If `n` is not an ISP of this day.
    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
            ),
        )
    }

    /// The ISP that contains `t`, if `t` falls in this day.
    #[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)
    }

    /// Checks a list of ISP elements against the two rules of `[UFTP §4.2.1]`: no ISP
    /// twice, and no element past the end of the day.
    ///
    /// # Errors
    /// On the first ISP addressed twice, or the first element that crosses the period.
    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(())
    }
}