1use core::fmt;
2
3use crate::time::{Date, DateTime, Time};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum Value<'a> {
8 None,
10 Int(i64),
12 UInt(u64),
15 Bcd(i64),
17 InvalidBcd(&'a [u8]),
20 Real32(u32),
24 Date(Date),
26 Time(Time),
28 DateTime(DateTime),
30 Text(&'a [u8]),
32 Bytes(&'a [u8]),
34 Duration(Quantity),
37}
38
39impl fmt::Display for Value<'_> {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 match *self {
46 Self::None => f.write_str("—"),
47 Self::Int(v) | Self::Bcd(v) => write!(f, "{v}"),
48 Self::UInt(v) => write!(f, "{v}"),
49 Self::InvalidBcd(b) => {
50 f.write_str("invalid BCD ")?;
51 hex(f, b.iter().rev())
52 }
53 Self::Real32(bits) => match real32_exact(bits) {
54 Some((mantissa, exponent)) => write!(f, "{}", Quantity { mantissa, exponent, unit: None }),
55 None => write!(f, "IEEE 754 0x{bits:08X}"),
56 },
57 Self::Date(d) => write!(f, "{d}"),
58 Self::Time(t) => write!(f, "{t}"),
59 Self::DateTime(t) => write!(f, "{t}"),
60 Self::Text(t) => escaped(f, t.iter().rev()),
61 Self::Bytes(b) => hex(f, b.iter()),
62 Self::Duration(q) => write!(f, "{q}"),
63 }
64 }
65}
66
67pub(crate) fn escaped<'b>(f: &mut fmt::Formatter<'_>, bytes: impl Iterator<Item = &'b u8>) -> fmt::Result {
69 for &b in bytes {
70 if b == b' ' || b.is_ascii_graphic() && b != b'\\' {
71 write!(f, "{}", char::from(b))?;
72 } else {
73 write!(f, "\\x{b:02x}")?;
74 }
75 }
76 Ok(())
77}
78
79fn hex<'b>(f: &mut fmt::Formatter<'_>, bytes: impl Iterator<Item = &'b u8>) -> fmt::Result {
80 for &b in bytes {
81 write!(f, "{b:02X}")?;
82 }
83 Ok(())
84}
85
86impl Value<'_> {
87 pub fn as_decimal(&self) -> Option<(i128, i8)> {
92 match *self {
93 Self::Real32(bits) => real32_exact(bits),
94 _ => self.as_integer().map(|m| (m, 0)),
95 }
96 }
97
98 pub const fn as_integer(&self) -> Option<i128> {
100 match *self {
101 Self::Int(v) | Self::Bcd(v) => Some(v as i128),
102 Self::UInt(v) => Some(v as i128),
103 _ => None,
104 }
105 }
106
107 pub(crate) const fn negate(self) -> Self {
108 match self {
109 Self::Bcd(v) => Self::Bcd(-v),
110 other => other,
111 }
112 }
113}
114
115fn real32_exact(bits: u32) -> Option<(i128, i8)> {
117 let negative = bits >> 31 != 0;
118 let biased = (bits >> 23) & 0xFF;
119 let fraction = bits & 0x007F_FFFF;
120 if biased == 0xFF {
121 return None; }
123 let (mut m, mut e) = if biased == 0 {
124 (i128::from(fraction), -149i32)
125 } else {
126 (i128::from(fraction | 0x0080_0000), i32::try_from(biased).ok()? - 150)
127 };
128 if m == 0 {
129 return Some((0, 0));
130 }
131 while m % 2 == 0 {
132 m /= 2;
133 e += 1;
134 }
135 let (mantissa, exponent) = if e >= 0 {
136 (m.checked_mul(2i128.checked_pow(e.unsigned_abs())?)?, 0)
137 } else {
138 let k = e.unsigned_abs();
139 (m.checked_mul(5i128.checked_pow(k)?)?, i8::try_from(e).ok()?)
140 };
141 Some((if negative { -mantissa } else { mantissa }, exponent))
142}
143
144pub(crate) fn le_signed(bytes: &[u8]) -> i64 {
146 let negative = bytes.last().is_some_and(|b| b & 0x80 != 0);
147 let start: u64 = if negative { u64::MAX } else { 0 };
148 let raw = bytes.iter().rev().fold(start, |acc, &b| (acc << 8) | u64::from(b));
149 i64::from_le_bytes(raw.to_le_bytes())
150}
151
152pub(crate) fn type_m(bytes: &[u8]) -> Option<Quantity> {
157 let (&header, count) = bytes.split_last()?;
158 if header & 0x1F != 0x10 || count.is_empty() || count.len() > 8 {
159 return None;
160 }
161 let c = i128::from(le_signed(count));
162 let min = -(1i128 << (8 * count.len() - 1));
163 if c == min {
164 return None;
165 }
166 let (factor, exponent) = match (header >> 5) & 0x03 {
168 0 => (2, 0),
169 1 => (1, 0),
170 2 => (390_625, -8),
171 _ => (30_517_578_125, -15),
172 };
173 let (mut mantissa, mut exponent) = (c.checked_mul(factor)?, exponent);
175 while exponent < 0 && mantissa % 10 == 0 {
176 mantissa /= 10;
177 exponent += 1;
178 }
179 Some(Quantity { mantissa, exponent, unit: Some(Unit::Seconds) })
180}
181
182pub(crate) fn le_unsigned(bytes: &[u8]) -> u64 {
184 bytes.iter().rev().fold(0u64, |acc, &b| (acc << 8) | u64::from(b))
185}
186
187pub(crate) fn bcd(bytes: &[u8]) -> Value<'_> {
190 let mut v: i64 = 0;
191 let mut negative = false;
192 for (i, &b) in bytes.iter().enumerate().rev() {
193 for (j, digit) in [b >> 4, b & 0x0F].into_iter().enumerate() {
194 let most_significant = i + 1 == bytes.len() && j == 0;
195 if digit > 9 {
196 if most_significant && digit == 0xF {
197 negative = true;
198 continue;
199 }
200 return Value::InvalidBcd(bytes);
201 }
202 v = v * 10 + i64::from(digit);
203 }
204 }
205 Value::Bcd(if negative { -v } else { v })
206}
207
208pub(crate) fn bcd_u32(bytes: [u8; 4]) -> Option<u32> {
210 match bcd(&bytes) {
211 Value::Bcd(v) => u32::try_from(v).ok(),
212 _ => None,
213 }
214}
215
216#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
218#[non_exhaustive]
219pub enum Unit {
220 Wh,
222 J,
224 M3,
226 Kg,
228 W,
230 JPerH,
232 M3PerH,
234 M3PerMin,
236 M3PerS,
238 KgPerH,
240 Celsius,
242 Kelvin,
244 Bar,
246 Seconds,
248 Minutes,
250 Hours,
252 Days,
254 Months,
256 Years,
258 Volt,
260 Ampere,
262 Hertz,
264 Percent,
266 Fahrenheit,
268 Calorie,
270 CubicFeet,
272 UsGallon,
274 UsGallonPerMin,
276 UsGallonPerH,
278 VoltAmpere,
280 Var,
282 VaH,
284 VarH,
286 Degree,
288 Dbm,
290 Currency,
292 Baud,
294 BitTimes,
296 Ppm,
298 Ppb,
300 MicrogramPerM3,
302 PerM3,
304 Lux,
306 Candela,
308 WattPerM2,
310 MetrePerS,
312 Dba,
314 Fnu,
316 Ph,
318 Millimetre,
320}
321
322impl Unit {
323 pub(crate) const fn duration(nn: u8) -> Self {
325 match nn & 0x03 {
326 0 => Self::Seconds,
327 1 => Self::Minutes,
328 2 => Self::Hours,
329 _ => Self::Days,
330 }
331 }
332
333 pub(crate) const fn long_duration(pp: u8) -> Self {
335 match pp & 0x03 {
336 0 => Self::Hours,
337 1 => Self::Days,
338 2 => Self::Months,
339 _ => Self::Years,
340 }
341 }
342
343 pub const fn symbol(self) -> &'static str {
345 match self {
346 Self::Wh => "Wh",
347 Self::J => "J",
348 Self::M3 => "m³",
349 Self::Kg => "kg",
350 Self::W => "W",
351 Self::JPerH => "J/h",
352 Self::M3PerH => "m³/h",
353 Self::M3PerMin => "m³/min",
354 Self::M3PerS => "m³/s",
355 Self::KgPerH => "kg/h",
356 Self::Celsius => "°C",
357 Self::Kelvin => "K",
358 Self::Bar => "bar",
359 Self::Seconds => "s",
360 Self::Minutes => "min",
361 Self::Hours => "h",
362 Self::Days => "d",
363 Self::Months => "months",
364 Self::Years => "years",
365 Self::Volt => "V",
366 Self::Ampere => "A",
367 Self::Hertz => "Hz",
368 Self::Percent => "%",
369 Self::Fahrenheit => "°F",
370 Self::Calorie => "cal",
371 Self::CubicFeet => "ft³",
372 Self::UsGallon => "US gal",
373 Self::UsGallonPerMin => "US gal/min",
374 Self::UsGallonPerH => "US gal/h",
375 Self::VoltAmpere => "VA",
376 Self::Var => "var",
377 Self::VaH => "VAh",
378 Self::VarH => "varh",
379 Self::Degree => "°",
380 Self::Dbm => "dBm",
381 Self::Currency => "currency units",
382 Self::Baud => "Bd",
383 Self::BitTimes => "bit times",
384 Self::Ppm => "ppm",
385 Self::Ppb => "ppb",
386 Self::MicrogramPerM3 => "µg/m³",
387 Self::PerM3 => "/m³",
388 Self::Lux => "lx",
389 Self::Candela => "cd",
390 Self::WattPerM2 => "W/m²",
391 Self::MetrePerS => "m/s",
392 Self::Dba => "dB(A)",
393 Self::Fnu => "FNU",
394 Self::Ph => "pH",
395 Self::Millimetre => "mm",
396 }
397 }
398}
399
400impl fmt::Display for Unit {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 f.write_str(self.symbol())
403 }
404}
405
406#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub struct Quantity {
409 pub mantissa: i128,
411 pub exponent: i8,
413 pub unit: Option<Unit>,
415}
416
417impl Quantity {
418 pub fn to_scale(self, exponent: i8) -> Option<i128> {
421 let diff = i32::from(self.exponent) - i32::from(exponent);
422 let p = 10i128.checked_pow(diff.unsigned_abs())?;
423 if diff >= 0 {
424 self.mantissa.checked_mul(p)
425 } else {
426 (self.mantissa.checked_rem(p)? == 0).then(|| self.mantissa.checked_div(p)).flatten()
428 }
429 }
430}
431
432impl Quantity {
433 pub fn round(self, exponent: i8) -> Option<Self> {
437 if exponent <= self.exponent {
438 return Some(Self { mantissa: self.to_scale(exponent)?, exponent, unit: self.unit });
439 }
440 let diff = i32::from(exponent) - i32::from(self.exponent);
441 let p = 10i128.checked_pow(diff.unsigned_abs())?;
442 let q = self.mantissa.checked_div(p)?;
443 let r = self.mantissa.checked_rem(p)?;
444 let twice = r.unsigned_abs().checked_mul(2)?;
445 let half = p.unsigned_abs();
446 let away = twice > half || (twice == half && q % 2 != 0);
447 let mantissa = if away { q.checked_add(r.signum())? } else { q };
448 Some(Self { mantissa, exponent, unit: self.unit })
449 }
450
451 pub fn significant(self, digits: u32) -> Option<Self> {
453 let len = self.mantissa.unsigned_abs().checked_ilog10().map_or(1, |l| l + 1);
454 if len <= digits {
455 return Some(self);
456 }
457 let shift = i8::try_from(len - digits).ok()?;
458 self.round(self.exponent.checked_add(shift)?)
459 }
460}
461
462impl Unit {
463 const fn prefixable(self) -> bool {
465 matches!(
466 self,
467 Self::Wh
468 | Self::J
469 | Self::W
470 | Self::JPerH
471 | Self::VoltAmpere
472 | Self::Var
473 | Self::VaH
474 | Self::VarH
475 | Self::Calorie
476 )
477 }
478}
479
480impl fmt::Display for Quantity {
481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485 if let Some(unit) = self.unit.filter(|u| u.prefixable() && !f.alternate() && self.mantissa != 0) {
486 let len = self.mantissa.unsigned_abs().checked_ilog10().unwrap_or(0);
487 let magnitude = i32::try_from(len).unwrap_or(0) + i32::from(self.exponent);
488 let k = (magnitude / 3).clamp(0, 4);
489 if k > 0 {
490 let prefix =
491 ["", "k", "M", "G", "T"].get(usize::try_from(k).unwrap_or(0)).copied().unwrap_or("");
492 let shift = i8::try_from(3 * k).unwrap_or(0);
493 let scaled = Self {
494 mantissa: self.mantissa,
495 exponent: self.exponent.saturating_sub(shift),
496 unit: None,
497 };
498 return write!(f, "{scaled} {prefix}{unit}");
499 }
500 }
501 let mut digits = [0u8; 40];
502 let mut n = self.mantissa.unsigned_abs();
503 let mut len = 0usize;
504 loop {
505 if let Some(slot) = digits.get_mut(len) {
506 *slot = b'0' + u8::try_from(n % 10).unwrap_or(0);
507 }
508 len += 1;
509 n /= 10;
510 if n == 0 || len >= digits.len() {
511 break;
512 }
513 }
514 let digits = digits.get(..len).unwrap_or(&[]);
515 if self.mantissa < 0 {
516 f.write_str("-")?;
517 }
518 let exp = i32::from(self.exponent);
519 let put = |f: &mut fmt::Formatter<'_>, d: &u8| write!(f, "{}", char::from(*d));
520 if self.mantissa == 0 && exp >= 0 {
521 f.write_str("0")?;
522 } else if exp >= 0 {
523 for d in digits.iter().rev() {
524 put(f, d)?;
525 }
526 for _ in 0..exp {
527 f.write_str("0")?;
528 }
529 } else {
530 let frac = exp.unsigned_abs() as usize;
531 if len <= frac {
532 f.write_str("0.")?;
533 for _ in len..frac {
534 f.write_str("0")?;
535 }
536 for d in digits.iter().rev() {
537 put(f, d)?;
538 }
539 } else {
540 for (i, d) in digits.iter().rev().enumerate() {
541 if i == len - frac {
542 f.write_str(".")?;
543 }
544 put(f, d)?;
545 }
546 }
547 }
548 if let Some(unit) = self.unit {
549 write!(f, " {unit}")?;
550 }
551 Ok(())
552 }
553}
554
555#[cfg(test)]
556mod tests {
557 extern crate std;
558 use super::*;
559 use std::string::ToString;
560
561 #[test]
562 fn bcd_decoding() {
563 assert_eq!(bcd(&[0x37, 0x18, 0x02]), Value::Bcd(21837));
564 assert_eq!(bcd(&[0x13, 0x01]), Value::Bcd(113));
565 assert_eq!(bcd(&[0x45, 0xF1]), Value::Bcd(-145));
566 assert_eq!(bcd(&[0x4A, 0x01]), Value::InvalidBcd(&[0x4A, 0x01]));
567 assert_eq!(bcd_u32([0x78, 0x56, 0x34, 0x12]), Some(12_345_678));
568 }
569
570 #[test]
571 fn little_endian_integers() {
572 assert_eq!(le_signed(&[0x15, 0x31, 0x00]), 12565);
573 assert_eq!(le_signed(&[0xFF, 0xFF]), -1);
574 assert_eq!(le_signed(&[0x00, 0x80]), -32768);
575 }
576
577 #[test]
578 fn reals_are_exact_decimals() {
579 assert_eq!(real32_exact(0x4652_9447), Some((134_770_693_359_375, -10)));
581 assert_eq!(real32_exact(0x3F80_0000), Some((1, 0)));
582 assert_eq!(real32_exact(0xC000_0000), Some((-2, 0)));
583 assert_eq!(real32_exact(0x0000_0000), Some((0, 0)));
584 assert_eq!(real32_exact(0x7F80_0000), None); assert_eq!(real32_exact(0x7FC0_0000), None); assert_eq!(real32_exact(0x0000_0001), None); assert_eq!(real32_exact(0x7F7F_FFFF), None); }
589
590 #[test]
591 fn type_m_relative_durations() {
592 let d = |b: &[u8]| type_m(b).map(|q| q.to_string());
594 assert_eq!(d(&[0x03, 0x30]).as_deref(), Some("3 s"));
595 assert_eq!(d(&[0x80, 0xDD, 0x50]).as_deref(), Some("-34.5 s"));
596 assert_eq!(d(&[0x0A, 0x10]).as_deref(), Some("20 s"));
597 assert_eq!(d(&[0x00, 0x40, 0x70]).as_deref(), Some("0.5 s"));
598 assert_eq!(d(&[0x03, 0xB0]).as_deref(), Some("3 s"));
599 assert_eq!(d(&[0x81, 0x30]).as_deref(), Some("-127 s"));
600 assert_eq!(d(&[0x80, 0x30]), None, "most negative count: invalid");
601 assert_eq!(d(&[0x0B, 0x60, 0x01, 0x00, 0x21]), None, "absolute form stays raw");
602 }
603
604 #[test]
605 fn rounding_is_explicit_and_half_even() {
606 let q = |m, e| Quantity { mantissa: m, exponent: e, unit: None };
607 assert_eq!(q(218_370, 0).round(3), Some(q(218, 3)));
608 assert_eq!(q(2_185, 0).round(1), Some(q(218, 1)));
609 assert_eq!(q(2_175, 0).round(1), Some(q(218, 1)));
610 assert_eq!(q(-2_185, 0).round(1), Some(q(-218, 1)));
611 assert_eq!(q(12, 0).round(-2), Some(q(1200, -2)));
612 assert_eq!(q(134_770_693_359_375, -10).significant(9).unwrap().to_string(), "13477.0693");
613 }
614
615 #[test]
616 fn exact_display() {
617 let q = |m, e| Quantity { mantissa: m, exponent: e, unit: Some(Unit::M3) }.to_string();
618 assert_eq!(q(12565, -3), "12.565 m³");
619 assert_eq!(q(21837, 1), "218370 m³");
620 assert_eq!(q(5, -3), "0.005 m³");
621 assert_eq!(q(0, 3), "0 m³");
622 assert_eq!(q(0, -2), "0.00 m³");
623 let e = |m, e| Quantity { mantissa: m, exponent: e, unit: Some(Unit::Wh) };
624 assert_eq!(e(218_370, 0).to_string(), "218.370 kWh");
625 assert_eq!(std::format!("{:#}", e(218_370, 0)), "218370 Wh");
626 assert_eq!(e(37_402, 3).to_string(), "37.402 MWh");
627 assert_eq!(e(999, 0).to_string(), "999 Wh");
628 assert_eq!(e(-1_364, 0).to_string(), "-1.364 kWh");
629 assert_eq!(e(0, 3).to_string(), "0 Wh");
630 }
631}