1use core::fmt;
17
18use crate::app::Authenticity;
19use crate::time::{Date, DateTime, Time};
20use crate::value::{self, Quantity, Value};
21use crate::vif::{Description, Extension, Kind, MAX_EXTENSIONS, Modifier, RecordError, Vib};
22use crate::{Error, Result};
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Function {
27 Instantaneous,
29 Maximum,
31 Minimum,
33 DuringError,
35}
36
37impl fmt::Display for Function {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 f.write_str(match self {
40 Self::Instantaneous => "instantaneous",
41 Self::Maximum => "maximum",
42 Self::Minimum => "minimum",
43 Self::DuringError => "during error",
44 })
45 }
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum DataField {
51 None,
53 Int(u8),
55 Real32,
57 Bcd(u8),
59 Variable,
61 Selection,
63}
64
65impl DataField {
66 pub const fn size(self) -> Option<usize> {
68 match self {
69 Self::None | Self::Selection => Some(0),
70 Self::Int(n) | Self::Bcd(n) => Some(n as usize),
71 Self::Real32 => Some(4),
72 Self::Variable => None,
73 }
74 }
75
76 pub(crate) const fn from_nibble(n: u8) -> Self {
77 match n & 0x0F {
78 0x1 => Self::Int(1),
79 0x2 => Self::Int(2),
80 0x3 => Self::Int(3),
81 0x4 => Self::Int(4),
82 0x5 => Self::Real32,
83 0x6 => Self::Int(6),
84 0x7 => Self::Int(8),
85 0x8 => Self::Selection,
86 0x9 => Self::Bcd(1),
87 0xA => Self::Bcd(2),
88 0xB => Self::Bcd(3),
89 0xC => Self::Bcd(4),
90 0xD => Self::Variable,
91 0xE => Self::Bcd(6),
92 _ => Self::None,
94 }
95 }
96}
97
98pub(crate) fn lvar_len(lvar: u8) -> Result<usize> {
100 Ok(match lvar {
101 0x00..=0xBF => usize::from(lvar),
102 0xC0..=0xC9 => usize::from(lvar - 0xC0),
103 0xD0..=0xD9 => usize::from(lvar - 0xD0),
104 0xE0..=0xEF => usize::from(lvar - 0xE0),
105 0xF0..=0xF4 => 4 * usize::from(lvar - 0xEC),
106 0xF5 => 48,
107 0xF6 => 64,
108 other => return Err(Error::UnsupportedLvar(other)),
109 })
110}
111
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub struct Dib {
115 pub dif: u8,
117 pub function: Function,
119 pub data: DataField,
121 pub storage: u64,
123 pub tariff: u32,
125 pub subunit: u16,
127}
128
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub struct Record<'a> {
132 pub dib: Dib,
134 pub vib: Vib<'a>,
136 pub value: Value<'a>,
138 pub authenticity: Authenticity,
144 pub header: Option<&'a [u8]>,
146}
147
148impl Record<'_> {
149 pub fn description(&self) -> Description {
151 self.vib.description()
152 }
153
154 pub fn profile(&self) -> Option<crate::profile::Profile<'_>> {
158 let direction = self.vib.modifiers().find_map(|m| match m {
159 Modifier::CompactProfile(d) => Some(d),
160 _ => None,
161 })?;
162 match self.value {
163 Value::Text(b) | Value::Bytes(b) => crate::profile::Profile::parse(direction, b),
164 _ => None,
165 }
166 }
167
168 pub fn name(&self) -> &'static str {
170 self.vib.description().kind.name()
171 }
172
173 pub fn quantity(&self) -> Option<Quantity> {
183 if let Value::Duration(q) = self.value {
184 return Some(q);
185 }
186 let (mantissa, base) = self.value.as_decimal()?;
187 let d = self.vib.description();
188 let unit = match d.kind {
190 Kind::PlainText => None,
191 _ => Some(d.unit?),
192 };
193 let mut exponent = d.exponent.checked_add(base)?;
194 for m in self.vib.modifiers() {
195 match m {
196 Modifier::Scale(e) => exponent = exponent.checked_add(e)?,
197 m if m.keeps_quantity() => {}
198 _ => return None,
199 }
200 }
201 Some(Quantity { mantissa, exponent, unit })
202 }
203}
204
205impl fmt::Display for Record<'_> {
206 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 let d = self.vib.description();
216 match (d.kind, self.vib.plain_text()) {
217 (Kind::PlainText, Some(unit)) if self.quantity().is_none() => {
219 f.write_str("value in ")?;
220 value::escaped(f, unit.iter().rev())?;
221 }
222 (Kind::PlainText, Some(_)) => f.write_str("value")?,
223 (kind, _) => write!(f, "{kind}")?,
224 }
225 let shown = |m: &Modifier| !matches!(m, Modifier::Scale(_) | Modifier::Error(RecordError(0)));
227 for m in self.vib.modifiers().filter(shown) {
228 write!(f, " · {m}")?;
229 }
230 let dib = &self.dib;
231 if dib.function != Function::Instantaneous {
232 write!(f, " · {}", dib.function)?;
233 }
234 if dib.storage != 0 {
235 write!(f, " · storage {}", dib.storage)?;
236 }
237 if dib.tariff != 0 {
238 write!(f, " · tariff {}", dib.tariff)?;
239 }
240 if dib.subunit != 0 {
241 write!(f, " · subunit {}", dib.subunit)?;
242 }
243 f.write_str(" — ")?;
244 match (self.quantity(), self.value) {
245 (Some(q), Value::Real32(_)) => match q.significant(9) {
247 Some(r) if r != q => write!(f, "≈ {r}")?,
248 _ => write!(f, "{q}")?,
249 },
250 (Some(q), Value::Duration(_)) => write!(f, "{q} before reception")?,
253 (Some(q), _) => write!(f, "{q}")?,
254 (None, _) if self.profile().is_some() => {
255 if let Some(p) = self.profile() {
256 write!(f, "{p}")?;
257 }
258 }
259 (None, value) => write!(f, "{value}")?,
260 }
261 if let (Some(_), Some(text)) = (self.quantity().filter(|q| q.unit.is_none()), self.vib.plain_text()) {
262 f.write_str(" ")?;
263 value::escaped(f, text.iter().rev())?;
264 }
265 Ok(())
266 }
267}
268
269#[derive(Clone, Debug)]
274pub struct Records<'a> {
275 buf: &'a [u8],
276 pos: usize,
277 done: bool,
278 manufacturer: Option<&'a [u8]>,
279 more_follows: bool,
280 protected_end: usize,
282 inside: Authenticity,
283 tail: Authenticity,
284}
285
286impl<'a> Records<'a> {
287 pub const fn new(buf: &'a [u8]) -> Self {
289 Self::protected(buf, 0, Authenticity::None, Authenticity::None)
290 }
291
292 pub(crate) const fn protected(
294 buf: &'a [u8],
295 end: usize,
296 inside: Authenticity,
297 tail: Authenticity,
298 ) -> Self {
299 Self {
300 buf,
301 pos: 0,
302 done: false,
303 manufacturer: None,
304 more_follows: false,
305 protected_end: end,
306 inside,
307 tail,
308 }
309 }
310
311 pub const fn manufacturer_data(&self) -> Option<&'a [u8]> {
313 self.manufacturer
314 }
315
316 pub const fn manufacturer_authenticity(&self) -> Authenticity {
320 if self.buf.len() <= self.protected_end { self.inside } else { self.tail }
321 }
322
323 pub const fn more_follows(&self) -> bool {
325 self.more_follows
326 }
327
328 fn byte(&mut self) -> Result<u8> {
329 let b = self.buf.get(self.pos).copied().ok_or(Error::UnexpectedEnd)?;
330 self.pos += 1;
331 Ok(b)
332 }
333
334 fn take(&mut self, n: usize) -> Result<&'a [u8]> {
335 let end = self.pos.checked_add(n).ok_or(Error::UnexpectedEnd)?;
336 let s = self.buf.get(self.pos..end).ok_or(Error::UnexpectedEnd)?;
337 self.pos = end;
338 Ok(s)
339 }
340
341 fn record(&mut self, dif: u8) -> Result<Record<'a>> {
342 let header_start = self.pos.saturating_sub(1);
343 let function = match (dif >> 4) & 0x03 {
344 0 => Function::Instantaneous,
345 1 => Function::Maximum,
346 2 => Function::Minimum,
347 _ => Function::DuringError,
348 };
349 let mut storage = u64::from((dif >> 6) & 1);
350 let mut tariff = 0u32;
351 let mut subunit = 0u16;
352 let mut ext = dif & 0x80 != 0;
353 let mut i = 0u32;
354 while ext {
355 if i as usize >= MAX_EXTENSIONS {
356 return Err(Error::TooManyExtensions);
357 }
358 let dife = self.byte()?;
359 storage |= u64::from(dife & 0x0F) << (1 + 4 * i);
360 tariff |= u32::from((dife >> 4) & 0x03) << (2 * i);
361 subunit |= u16::from((dife >> 6) & 1) << i;
362 ext = dife & 0x80 != 0;
363 i += 1;
364 }
365 let data = DataField::from_nibble(dif);
366 let dib = Dib { dif, function, data, storage, tariff, subunit };
367
368 let start = self.pos;
372 match self.value_part(dib, false, header_start) {
373 Err(e) if self.buf.get(start) == Some(&0xFC) => {
374 self.pos = start;
375 self.value_part(dib, true, header_start).map_err(|_| e)
376 }
377 r => r,
378 }
379 }
380
381 fn plain_text(&mut self) -> Result<&'a [u8]> {
382 let n = self.byte()?;
383 self.take(usize::from(n))
384 }
385
386 fn value_part(&mut self, dib: Dib, text_first: bool, header_start: usize) -> Result<Record<'a>> {
387 let data = dib.data;
388 let vif = self.byte()?;
389 let mut plain_text = if text_first { Some(self.plain_text()?) } else { None };
390 let mut vifes = [0u8; MAX_EXTENSIONS];
391 let mut vife_len = 0u8;
392 let mut ext = vif & 0x80 != 0;
393 while ext {
394 let vife = self.byte()?;
395 *vifes.get_mut(usize::from(vife_len)).ok_or(Error::TooManyExtensions)? = vife;
396 vife_len += 1;
397 ext = vife & 0x80 != 0;
398 }
399 let header = (vif & 0x7F != 0x7C).then(|| self.buf.get(header_start..self.pos)).flatten();
401 if vif & 0x7F == 0x7C && plain_text.is_none() {
402 plain_text = Some(self.plain_text()?);
403 }
404 let vib = Vib::new(vif, vifes, vife_len, plain_text);
405 let time_point =
406 vib.description().kind.is_time_point() || vib.modifiers().any(Modifier::is_time_point);
407 let unsigned = vib.modifiers().any(|m| m == Modifier::Extension(Extension::Unsigned));
408
409 let value = match data {
410 DataField::None | DataField::Selection => Value::None,
411 DataField::Int(n) => {
412 let bytes = self.take(usize::from(n))?;
413 match (time_point, bytes) {
414 (true, &[b0, b1]) => Value::Date(Date::from_type_g(b0, b1)),
415 (true, &[b0, b1, b2]) => Value::Time(Time::from_type_j(b0, b1, b2)),
416 (true, &[b0, b1, b2, b3]) => Value::DateTime(DateTime::from_type_f([b0, b1, b2, b3])),
417 (true, &[b0, b1, b2, b3, b4, b5]) => {
418 Value::DateTime(DateTime::from_type_i([b0, b1, b2, b3, b4, b5]))
419 }
420 _ if unsigned => Value::UInt(value::le_unsigned(bytes)),
421 _ => Value::Int(value::le_signed(bytes)),
422 }
423 }
424 DataField::Real32 => {
425 let b = self.take(4)?;
426 Value::Real32(u32::from_le_bytes(b.try_into().map_err(|_| Error::UnexpectedEnd)?))
427 }
428 DataField::Bcd(n) => value::bcd(self.take(usize::from(n))?),
429 DataField::Variable => {
430 let lvar = self.byte()?;
431 match lvar {
432 0x00..=0xBF => Value::Text(self.take(usize::from(lvar))?),
433 0xC0..=0xC9 => value::bcd(self.take(usize::from(lvar - 0xC0))?),
434 0xD0..=0xD9 => value::bcd(self.take(usize::from(lvar - 0xD0))?).negate(),
435 0xE0..=0xEF => {
436 let bytes = self.take(usize::from(lvar - 0xE0))?;
437 if let Some(d) = time_point.then(|| value::type_m(bytes)).flatten() {
438 Value::Duration(d)
439 } else if bytes.len() <= 8 {
440 Value::Int(value::le_signed(bytes))
441 } else {
442 Value::Bytes(bytes)
443 }
444 }
445 0xF0..=0xF4 => Value::Bytes(self.take(4 * usize::from(lvar - 0xEC))?),
448 0xF5 => Value::Bytes(self.take(48)?),
449 0xF6 => Value::Bytes(self.take(64)?),
450 other => return Err(Error::UnsupportedLvar(other)),
451 }
452 }
453 };
454 Ok(Record { dib, vib, value, authenticity: Authenticity::None, header })
455 }
456}
457
458impl<'a> Iterator for Records<'a> {
459 type Item = Result<Record<'a>>;
460
461 fn next(&mut self) -> Option<Self::Item> {
462 while !self.done {
463 let Some(&dif) = self.buf.get(self.pos) else {
464 self.done = true;
465 return None;
466 };
467 self.pos += 1;
468 match dif {
469 0x2F | 0x7F => {}
471 0x0F | 0x1F => {
472 self.more_follows = dif == 0x1F;
473 self.manufacturer = Some(self.buf.get(self.pos..).unwrap_or(&[]));
474 self.done = true;
475 return None;
476 }
477 d if d & 0x0F == 0x0F => {
478 self.done = true;
479 return Some(Err(Error::ReservedDif(d)));
480 }
481 d => {
482 let r = self.record(d).map(|mut r| {
483 r.authenticity = if self.pos <= self.protected_end { self.inside } else { self.tail };
485 r
486 });
487 self.done = r.is_err();
488 return Some(r);
489 }
490 }
491 }
492 None
493 }
494}
495
496#[cfg(test)]
497mod tests {
498 extern crate std;
499 use super::*;
500 use std::string::ToString;
501
502 #[test]
503 fn storage_tariff_and_subunit_from_extensions() {
504 let mut r = Records::new(&[0xDA, 0x02, 0x3B, 0x13, 0x01]);
506 let rec = r.next().unwrap().unwrap();
507 assert_eq!(rec.dib.storage, 5);
508 assert_eq!(rec.dib.function, Function::Maximum);
509 assert_eq!(rec.dib.data, DataField::Bcd(2));
510 assert_eq!(rec.value, Value::Bcd(113));
511 let rec = Records::new(&[0x8B, 0x60, 0x04, 0x37, 0x18, 0x02]).next().unwrap().unwrap();
513 assert_eq!((rec.dib.storage, rec.dib.tariff, rec.dib.subunit), (0, 2, 1));
514 }
515
516 #[test]
517 fn filler_and_manufacturer_data() {
518 let mut r = Records::new(&[0x2F, 0x2F, 0x01, 0xFD, 0x08, 0x05, 0x0F, 0xAA, 0xBB]);
519 let rec = r.next().unwrap().unwrap();
520 assert_eq!(rec.vib.vif(), 0xFD);
521 assert_eq!(rec.vib.vifes(), &[0x08]);
522 assert_eq!(rec.name(), "access number");
523 assert_eq!(rec.value, Value::Int(5));
524 assert!(r.next().is_none());
525 assert_eq!(r.manufacturer_data(), Some(&[0xAA, 0xBB][..]));
526 assert!(!r.more_follows());
527 }
528
529 #[test]
530 fn plain_text_vif() {
531 let rec = Records::new(&[0x01, 0x7C, 0x03, b'a', b'P', b'h', 0x2A]).next().unwrap().unwrap();
533 assert_eq!(rec.vib.plain_text(), Some(&b"aPh"[..]));
534 assert_eq!(rec.to_string(), "value — 42 hPa");
535 assert_eq!(rec.value, Value::Int(42));
536 }
537
538 #[test]
539 fn plain_text_after_vifes_and_the_elvaco_deviation() {
540 let rec =
542 Records::new(&[0x0C, 0xFC, 0xA2, 0x73, 0x04, b'l', b'a', b'g', b'i', 0x26, 0x08, 0x42, 0x75])
543 .next()
544 .unwrap()
545 .unwrap();
546 assert_eq!(rec.vib.plain_text(), Some(&b"lagi"[..]));
547 assert_eq!(rec.value, Value::Bcd(75_420_826));
548 assert_eq!(rec.to_string(), "value in igal · per hour — 75420826");
549 let rec =
551 Records::new(&[0x02, 0xFC, 0x03, b'H', b'R', b'%', 0x74, 0x22, 0x15]).next().unwrap().unwrap();
552 assert_eq!(rec.vib.plain_text(), Some(&b"HR%"[..]));
553 assert_eq!(rec.vib.vifes(), &[0x74]);
554 assert_eq!(rec.value, Value::Int(0x1522));
555 }
556
557 #[test]
558 fn too_many_extensions() {
559 let input = [0x84u8, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00];
560 assert_eq!(Records::new(&input).next(), Some(Err(Error::TooManyExtensions)));
561 }
562
563 #[test]
564 fn truncation_is_an_error() {
565 let full = [0x04u8, 0x13, 0x01, 0x02, 0x03, 0x04];
566 for cut in 1..full.len() {
567 assert!(matches!(Records::new(&full[..cut]).next(), Some(Err(_))), "cut {cut}");
568 }
569 }
570}