entsoe-edi 0.49.0

ENTSO-E ESS 2.3 schedule documents for German intra-area electricity trades
Documentation
#![doc = include_str!("../README.md")]
#![forbid(unsafe_code)]

mod schedule;

use std::fmt;

pub use rubo4e::identifiers::{BilanzierungsgebietId, BilanzkreisId, EicCode};
pub use schedule::{ScheduleError, ScheduleMessage, TradeSeries, delivery_window};

/// An ESS interval quantity in whole kilowatts, displayed in megawatts.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ScheduleQuantity(u64);

impl ScheduleQuantity {
    /// Refuses quantities whose shortest exact MW representation exceeds 17 characters.
    #[must_use = "the quantity may exceed the ESS wire limit"]
    pub fn from_kw(kw: u64) -> Result<Self, ScheduleError> {
        let quantity = Self(kw);
        let (_, places) = quantity.fraction();
        let whole_digits = (kw / 1000).checked_ilog10().unwrap_or(0) as usize + 1;
        if whole_digits + places + usize::from(places != 0) > 17 {
            return Err(ScheduleError::QuantityTooLong(kw));
        }
        Ok(quantity)
    }

    fn fraction(self) -> (u64, usize) {
        let part = self.0 % 1000;
        match part {
            0 => (0, 0),
            n if n.is_multiple_of(100) => (n / 100, 1),
            n if n.is_multiple_of(10) => (n / 10, 2),
            n => (n, 3),
        }
    }
}

impl fmt::Display for ScheduleQuantity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0 / 1000)?;
        let (part, places) = self.fraction();
        if places != 0 {
            write!(f, ".{part:0places$}")?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn megawatts_preserve_every_kilowatt_within_the_wire_width() {
        for (kw, expected) in [
            (0, "0"),
            (1, "0.001"),
            (10, "0.01"),
            (100, "0.1"),
            (999, "0.999"),
            (1000, "1"),
            (3_500_043, "3500.043"),
            (9_999_999_999_999_999, "9999999999999.999"),
            (18_446_744_073_709_551_000, "18446744073709551"),
        ] {
            assert_eq!(ScheduleQuantity::from_kw(kw).unwrap().to_string(), expected);
        }
        for kw in [10_000_000_000_000_001, u64::MAX] {
            assert!(matches!(
                ScheduleQuantity::from_kw(kw),
                Err(ScheduleError::QuantityTooLong(_))
            ));
        }
    }
}