1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3
4mod schedule;
5
6use std::fmt;
7
8pub use rubo4e::identifiers::{BilanzierungsgebietId, BilanzkreisId, EicCode};
9pub use schedule::{ScheduleError, ScheduleMessage, TradeSeries, delivery_window};
10
11#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
13pub struct ScheduleQuantity(u64);
14
15impl ScheduleQuantity {
16 #[must_use = "the quantity may exceed the ESS wire limit"]
18 pub fn from_kw(kw: u64) -> Result<Self, ScheduleError> {
19 let quantity = Self(kw);
20 let (_, places) = quantity.fraction();
21 let whole_digits = (kw / 1000).checked_ilog10().unwrap_or(0) as usize + 1;
22 if whole_digits + places + usize::from(places != 0) > 17 {
23 return Err(ScheduleError::QuantityTooLong(kw));
24 }
25 Ok(quantity)
26 }
27
28 fn fraction(self) -> (u64, usize) {
29 let part = self.0 % 1000;
30 match part {
31 0 => (0, 0),
32 n if n.is_multiple_of(100) => (n / 100, 1),
33 n if n.is_multiple_of(10) => (n / 10, 2),
34 n => (n, 3),
35 }
36 }
37}
38
39impl fmt::Display for ScheduleQuantity {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 write!(f, "{}", self.0 / 1000)?;
42 let (part, places) = self.fraction();
43 if places != 0 {
44 write!(f, ".{part:0places$}")?;
45 }
46 Ok(())
47 }
48}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53
54 #[test]
55 fn megawatts_preserve_every_kilowatt_within_the_wire_width() {
56 for (kw, expected) in [
57 (0, "0"),
58 (1, "0.001"),
59 (10, "0.01"),
60 (100, "0.1"),
61 (999, "0.999"),
62 (1000, "1"),
63 (3_500_043, "3500.043"),
64 (9_999_999_999_999_999, "9999999999999.999"),
65 (18_446_744_073_709_551_000, "18446744073709551"),
66 ] {
67 assert_eq!(ScheduleQuantity::from_kw(kw).unwrap().to_string(), expected);
68 }
69 for kw in [10_000_000_000_000_001, u64::MAX] {
70 assert!(matches!(
71 ScheduleQuantity::from_kw(kw),
72 Err(ScheduleError::QuantityTooLong(_))
73 ));
74 }
75 }
76}