Skip to main content

flexpool_core/
units.rs

1//! Exact physical and monetary quantities.
2//!
3//! Only physically meaningful operations exist: power × duration is energy, energy × price is
4//! money, capacity price × power × duration is money. Adding power to energy does not compile.
5//! Same-unit arithmetic is checked: overflow yields `None`, never a wrapped value.
6//!
7//! ```compile_fail
8//! use flexpool_core::{Kw, Kwh};
9//! use rust_decimal::Decimal;
10//! let _ = Kw::new(Decimal::ONE).checked_add(Kwh::new(Decimal::ONE));
11//! ```
12
13use rust_decimal::Decimal;
14use serde::{Deserialize, Serialize};
15use time::Duration;
16
17const THOUSAND: Decimal = Decimal::from_parts(1000, 0, 0, false, 0);
18const SECONDS_PER_HOUR: Decimal = Decimal::from_parts(3600, 0, 0, false, 0);
19
20/// Whole seconds of a duration as an exact decimal (sub-second parts are kept as nanoseconds).
21fn hours(duration: Duration) -> Option<Decimal> {
22    let nanos = Decimal::from_i128_with_scale(duration.whole_nanoseconds(), 9);
23    nanos.checked_div(SECONDS_PER_HOUR)
24}
25
26macro_rules! quantity {
27    ($(#[$meta:meta])* $name:ident, $unit:literal) => {
28        $(#[$meta])*
29        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
30        #[serde(transparent)]
31        pub struct $name(#[serde(with = "rust_decimal::serde::str")] Decimal);
32
33        impl $name {
34            /// Zero.
35            pub const ZERO: Self = Self(Decimal::ZERO);
36
37            /// Wraps an exact decimal in this unit.
38            #[must_use]
39            pub const fn new(value: Decimal) -> Self {
40                Self(value)
41            }
42
43            /// The exact value in this type's unit.
44            #[must_use]
45            pub const fn value(self) -> Decimal {
46                self.0
47            }
48
49            /// Checked addition; `None` on overflow.
50            #[must_use]
51            pub fn checked_add(self, other: Self) -> Option<Self> {
52                self.0.checked_add(other.0).map(Self)
53            }
54
55            /// Checked subtraction; `None` on overflow.
56            #[must_use]
57            pub fn checked_sub(self, other: Self) -> Option<Self> {
58                self.0.checked_sub(other.0).map(Self)
59            }
60
61        }
62
63        impl std::ops::Neg for $name {
64            type Output = Self;
65            /// The same magnitude with the opposite sign.
66            fn neg(self) -> Self {
67                Self(-self.0)
68            }
69        }
70
71        impl std::fmt::Display for $name {
72            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73                write!(f, "{} {}", self.0.normalize(), $unit)
74            }
75        }
76    };
77}
78
79quantity!(
80    /// Power in kilowatts. Positive is consumption (import), negative is feed-in (export).
81    Kw,
82    "kW"
83);
84quantity!(
85    /// Energy in kilowatt-hours.
86    Kwh,
87    "kWh"
88);
89quantity!(
90    /// Money in euros, kept at full precision until [`Eur::round_cents`].
91    Eur,
92    "EUR"
93);
94quantity!(
95    /// Energy price in euros per megawatt-hour (day-ahead, intraday, aFRR energy).
96    EurPerMwh,
97    "EUR/MWh"
98);
99quantity!(
100    /// Capacity price in euros per megawatt and hour (FCR, aFRR capacity).
101    EurPerMwPerH,
102    "EUR/MW/h"
103);
104
105impl Kw {
106    /// Power from megawatts, exactly (× 1000).
107    #[must_use]
108    pub fn from_mw(mw: Decimal) -> Option<Self> {
109        mw.checked_mul(THOUSAND).map(Self)
110    }
111
112    /// This power in megawatts, exactly.
113    #[must_use]
114    pub fn to_mw(self) -> Decimal {
115        self.0 / THOUSAND
116    }
117
118    /// Energy delivered at this power for `duration`; `None` on overflow.
119    #[must_use]
120    pub fn energy_over(self, duration: Duration) -> Option<Kwh> {
121        hours(duration).and_then(|h| self.0.checked_mul(h)).map(Kwh)
122    }
123}
124
125impl Kwh {
126    /// Energy from megawatt-hours, exactly (× 1000).
127    #[must_use]
128    pub fn from_mwh(mwh: Decimal) -> Option<Self> {
129        mwh.checked_mul(THOUSAND).map(Self)
130    }
131
132    /// This energy in megawatt-hours, exactly.
133    #[must_use]
134    pub fn to_mwh(self) -> Decimal {
135        self.0 / THOUSAND
136    }
137
138    /// Mean power over `duration`; `None` for a zero duration or overflow.
139    #[must_use]
140    pub fn mean_power_over(self, duration: Duration) -> Option<Kw> {
141        hours(duration).and_then(|h| self.0.checked_div(h)).map(Kw)
142    }
143
144    /// The value of this energy at `price`; `None` on overflow.
145    #[must_use]
146    pub fn priced_at(self, price: EurPerMwh) -> Option<Eur> {
147        self.to_mwh().checked_mul(price.0).map(Eur)
148    }
149}
150
151impl EurPerMwPerH {
152    /// Capacity remuneration for holding `power` for `duration`; `None` on overflow.
153    #[must_use]
154    pub fn for_capacity(self, power: Kw, duration: Duration) -> Option<Eur> {
155        let mw_h = hours(duration).and_then(|h| power.to_mw().checked_mul(h))?;
156        self.0.checked_mul(mw_h).map(Eur)
157    }
158}
159
160impl Eur {
161    /// Rounded to whole cents, half to even (banker's rounding), for statements and invoices.
162    #[must_use]
163    pub fn round_cents(self) -> Self {
164        Self(
165            self.0
166                .round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointNearestEven),
167        )
168    }
169}
170
171/// Parses a plain decimal as written in data files: optional minus, digits, optional fraction.
172/// Underscores, exponents, a leading `+` and whitespace are refused — `1_0.5` is not 10.5.
173#[must_use]
174pub fn parse_plain(s: &str) -> Option<Decimal> {
175    let body = s.strip_prefix('-').unwrap_or(s);
176    let (int, frac) = body.split_once('.').unwrap_or((body, ""));
177    let digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
178    let plain = digits(int) && (frac.is_empty() && !body.ends_with('.') || digits(frac));
179    if plain {
180        <Decimal as std::str::FromStr>::from_str(s).ok()
181    } else {
182        None
183    }
184}