1use crate::{taf2::TariffRegister, taf7::Channel};
10use core::fmt;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Register {
15 Meter,
16 DerivedTotal,
17 DerivedTariff(TariffRegister),
18 DerivedError,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct Quantity<'a> {
24 pub profile_id: &'a str,
25 pub channel: Channel<'a>,
26 pub register: Register,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct DailyBalance<'a> {
31 pub quantity: Quantity<'a>,
32 pub opening_utc: i64,
33 pub wh: u64,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Error {
38 EmptyIdentifier,
39 InvalidCalendar,
40 WrongQuantity,
41 OutsideCalendar,
42 NotDayOpening,
43 DayAlreadyRecorded,
44 DayWentBackwards,
45}
46
47impl fmt::Display for Error {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 f.write_str(match self {
50 Self::EmptyIdentifier => "supply the evaluation profile and meter identifiers",
51 Self::InvalidCalendar => "supply ordered daily openings and a final exclusive boundary",
52 Self::WrongQuantity => "profile, channel or register does not match the history",
53 Self::OutsideCalendar => "the billing calendar does not cover this instant",
54 Self::NotDayOpening => "expected the exact opening of a billing day",
55 Self::DayAlreadyRecorded => "the opening balance has already been recorded",
56 Self::DayWentBackwards => "cannot move the billing day backwards",
57 })
58 }
59}
60
61impl core::error::Error for Error {}
62
63const DAYS: usize = 42;
64
65pub struct History<'a> {
67 quantity: Quantity<'a>,
68 boundaries: &'a [i64],
69 current_day: Option<usize>,
70 balances: [Option<u64>; DAYS],
71}
72
73impl<'a> History<'a> {
74 pub fn new(quantity: Quantity<'a>, boundaries: &'a [i64]) -> Result<Self, Error> {
77 if quantity.profile_id.trim().is_empty() || quantity.channel.meter_id.trim().is_empty() {
78 return Err(Error::EmptyIdentifier);
79 }
80 if boundaries.len() < 2
82 || boundaries
83 .windows(2)
84 .any(|pair| !matches!(pair[1].checked_sub(pair[0]), Some(82_800 | 86_400 | 90_000)))
85 {
86 return Err(Error::InvalidCalendar);
87 }
88 Ok(Self {
89 quantity,
90 boundaries,
91 current_day: None,
92 balances: [None; DAYS],
93 })
94 }
95
96 pub fn record(
98 &mut self,
99 quantity: Quantity<'_>,
100 opening_utc: i64,
101 wh: u64,
102 ) -> Result<(), Error> {
103 if quantity != self.quantity {
104 return Err(Error::WrongQuantity);
105 }
106 let day = self.day_at(opening_utc)?;
107 if self.boundaries[day] != opening_utc {
108 return Err(Error::NotDayOpening);
109 }
110 self.advance(day)?;
111 let slot = &mut self.balances[day % DAYS];
112 if slot.is_some() {
113 return Err(Error::DayAlreadyRecorded);
114 }
115 *slot = Some(wh);
116 Ok(())
117 }
118
119 pub fn advance_to(&mut self, now_utc: i64) -> Result<(), Error> {
121 self.advance(self.day_at(now_utc)?)
122 }
123
124 pub fn lookup(
127 &mut self,
128 quantity: Quantity<'_>,
129 opening_utc: i64,
130 now_utc: i64,
131 ) -> Result<Option<DailyBalance<'a>>, Error> {
132 if quantity != self.quantity {
133 return Err(Error::WrongQuantity);
134 }
135 let today = self.day_at(now_utc)?;
136 self.advance(today)?;
137 let Ok(day) = self.boundaries.binary_search(&opening_utc) else {
138 return Ok(None);
139 };
140 if day > today || today - day >= DAYS {
141 return Ok(None);
142 }
143 Ok(self.balances[day % DAYS].map(|wh| DailyBalance {
144 quantity: self.quantity,
145 opening_utc,
146 wh,
147 }))
148 }
149
150 fn day_at(&self, instant: i64) -> Result<usize, Error> {
151 let end = self.boundaries.partition_point(|&start| start <= instant);
152 if end == 0 || end == self.boundaries.len() {
153 Err(Error::OutsideCalendar)
154 } else {
155 Ok(end - 1)
156 }
157 }
158
159 fn advance(&mut self, day: usize) -> Result<(), Error> {
160 if let Some(previous) = self.current_day {
161 let elapsed = day.checked_sub(previous).ok_or(Error::DayWentBackwards)?;
162 for offset in 0..elapsed.min(DAYS) {
164 self.balances[(day - offset) % DAYS] = None;
165 }
166 }
167 self.current_day = Some(day);
168 Ok(())
169 }
170}