Skip to main content

ocpi_tariffs/
energy.rs

1//! Types to represent energy.
2
3use rust_decimal::Decimal;
4use rust_decimal_macros::dec;
5
6use crate::{
7    Money, impl_dec_newtype,
8    money::Cost,
9    number::{FromDecimal as _, IsZero, approx_eq_dec},
10};
11
12impl_dec_newtype!(Ampere, "A");
13impl_dec_newtype!(Kw, "kW");
14impl_dec_newtype!(Kwh, "kWh");
15
16/// A value of kilo watt hours.
17#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Default)]
18#[cfg_attr(test, derive(serde::Deserialize))]
19pub struct Kwh(Decimal);
20
21impl IsZero for Kwh {
22    fn is_zero(&self) -> bool {
23        const TOLERANCE: Decimal = dec!(0.001);
24
25        approx_eq_dec(&self.0, &Decimal::ZERO, TOLERANCE)
26    }
27}
28
29impl Cost for Kwh {
30    fn cost(&self, money: Money) -> Money {
31        let cost = self.0.saturating_mul(money.into());
32        Money::from_decimal(cost)
33    }
34}
35
36const KILO: Decimal = dec!(1000);
37
38impl Kwh {
39    #[must_use]
40    pub(crate) const fn zero() -> Self {
41        Self(Decimal::ZERO)
42    }
43
44    /// Return the value in watt hours, rather than the kilowatt hours it is stored as.
45    pub fn watt_hours(self) -> Decimal {
46        self.0.saturating_mul(KILO)
47    }
48
49    #[expect(clippy::missing_panics_doc, reason = "divisor is non-zero")]
50    #[expect(clippy::unwrap_used, reason = "divisor is non-zero")]
51    /// Build a value from an amount given in watt hours.
52    pub fn from_watt_hours(num: Decimal) -> Self {
53        Self(num.checked_div(KILO).unwrap())
54    }
55}
56
57/// A value of kilo watts.
58#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
59pub struct Kw(Decimal);
60
61impl IsZero for Kw {
62    fn is_zero(&self) -> bool {
63        const TOLERANCE: Decimal = dec!(0.001);
64
65        approx_eq_dec(&self.0, &Decimal::ZERO, TOLERANCE)
66    }
67}
68
69/// A value of amperes.
70#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
71pub struct Ampere(Decimal);
72
73impl IsZero for Ampere {
74    fn is_zero(&self) -> bool {
75        const TOLERANCE: Decimal = dec!(0.001);
76
77        approx_eq_dec(&self.0, &Decimal::ZERO, TOLERANCE)
78    }
79}