use core::fmt;
use crate::message::ParseOptions;
use crate::tl::{Kind, Reader, Writer};
use crate::{Error, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SmlValue<'a> {
Bool(bool),
Bytes(&'a [u8]),
Int(i64),
Uint(u64),
Time(Time),
}
impl<'a> SmlValue<'a> {
pub fn as_integer(&self) -> Option<i128> {
match *self {
Self::Int(v) => Some(i128::from(v)),
Self::Uint(v) => Some(i128::from(v)),
Self::Bool(_) | Self::Bytes(_) | Self::Time(_) => None,
}
}
pub(crate) fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<(Self, usize)> {
let tl = r.clone().read_tl()?;
Ok(match tl.kind {
Kind::Boolean => (Self::Bool(r.boolean()?), 0),
Kind::OctetString => (Self::Bytes(r.octet_string()?), 0),
Kind::Integer => (Self::Int(r.integer()?), tl.len),
Kind::Unsigned => (Self::Uint(r.unsigned()?), tl.len),
Kind::List => {
r.list(2)?;
match r.unsigned()? {
1 => (Self::Time(Time::read(r, options)?), 0),
choice => return Err(Error::UnknownChoice { what: "SML_Value", choice }),
}
}
})
}
pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
match *self {
Self::Bool(b) => w.boolean(b),
Self::Bytes(b) => w.octet_string(b),
Self::Int(v) => w.integer_min(v),
Self::Uint(v) => w.unsigned_min(v),
Self::Time(t) => {
w.list(2)?;
w.unsigned(1, 1)?;
t.write(w)
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Unit(pub u8);
impl Unit {
pub const CELSIUS: Self = Self(9);
#[doc(alias("CUBIC_METRE", "CUBIC_METER"))]
pub const M3: Self = Self(13);
#[doc(alias("CUBIC_METRE_CORRECTED", "CUBIC_METER_CORRECTED"))]
pub const M3_CORRECTED: Self = Self(14);
#[doc(alias("CUBIC_METRE_PER_HOUR", "CUBIC_METER_PER_HOUR"))]
pub const M3_PER_H: Self = Self(15);
#[doc(alias("CUBIC_METRE_PER_HOUR_CORRECTED", "CUBIC_METER_PER_HOUR_CORRECTED"))]
pub const M3_PER_H_CORRECTED: Self = Self(16);
pub const W: Self = Self(27);
pub const VA: Self = Self(28);
pub const VAR: Self = Self(29);
pub const WH: Self = Self(30);
pub const VAH: Self = Self(31);
pub const VARH: Self = Self(32);
pub const A: Self = Self(33);
pub const V: Self = Self(35);
pub const HZ: Self = Self(44);
pub const PERCENT: Self = Self(56);
pub const COUNT: Self = Self(255);
pub const fn symbol(self) -> Option<&'static str> {
Some(match self.0 {
1 => "a",
2 => "mo",
3 => "wk",
4 => "d",
5 => "h",
6 => "min",
7 => "s",
8 => "°",
9 => "°C",
10 => "currency",
11 => "m",
12 => "m/s",
13 | 14 => "m³",
15 | 16 => "m³/h",
17 | 18 => "m³/d",
19 => "l",
20 => "kg",
21 => "N",
22 => "Nm",
23 => "Pa",
24 => "bar",
25 => "J",
26 => "J/h",
27 => "W",
28 => "VA",
29 => "var",
30 => "Wh",
31 => "VAh",
32 => "varh",
33 => "A",
34 => "C",
35 => "V",
36 => "V/m",
37 => "F",
38 => "Ω",
39 => "Ωm²/m",
40 => "Wb",
41 => "T",
42 => "A/m",
43 => "H",
44 => "Hz",
45 => "1/(Wh)",
46 => "1/(varh)",
47 => "1/(VAh)",
48 => "V²h",
49 => "A²h",
50 => "kg/s",
51 => "S",
52 => "K",
53 => "1/(V²h)",
54 => "1/(A²h)",
55 => "1/m³",
56 => "%",
255 => "",
_ => return None,
})
}
}
impl fmt::Display for Unit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.symbol() {
Some(s) => f.write_str(s),
None => write!(f, "unit({})", self.0),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Quantity {
pub mantissa: i128,
pub exponent: i8,
pub unit: Option<Unit>,
}
impl Quantity {
pub fn to_scale(self, exponent: i8) -> Option<i128> {
let diff = i32::from(self.exponent) - i32::from(exponent);
if diff >= 0 {
10i128.checked_pow(diff.unsigned_abs()).and_then(|p| self.mantissa.checked_mul(p))
} else {
let p = 10i128.checked_pow(diff.unsigned_abs())?;
(self.mantissa % p == 0).then(|| self.mantissa / p)
}
}
}
impl fmt::Display for Quantity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut digits = [0u8; 40];
let mut n = self.mantissa.unsigned_abs();
let mut len = 0usize;
loop {
if let Some(slot) = digits.get_mut(len) {
*slot = b'0' + (n % 10) as u8;
}
len += 1;
n /= 10;
if n == 0 || len >= digits.len() {
break;
}
}
let digits = digits.get(..len).unwrap_or(&[]);
if self.mantissa < 0 {
f.write_str("-")?;
}
let exp = i32::from(self.exponent);
if exp >= 0 {
for d in digits.iter().rev() {
write!(f, "{}", char::from(*d))?;
}
for _ in 0..exp {
f.write_str("0")?;
}
} else {
let frac = exp.unsigned_abs() as usize;
if len <= frac {
f.write_str("0.")?;
for _ in len..frac {
f.write_str("0")?;
}
for d in digits.iter().rev() {
write!(f, "{}", char::from(*d))?;
}
} else {
for (i, d) in digits.iter().rev().enumerate() {
if i == len - frac {
f.write_str(".")?;
}
write!(f, "{}", char::from(*d))?;
}
}
}
if let Some(unit) = self.unit.filter(|u| u.symbol() != Some("")) {
write!(f, " {unit}")?;
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Time {
SecIndex(u32),
Timestamp(u32),
LocalTimestamp {
timestamp: u32,
local_offset_minutes: i16,
season_offset_minutes: i16,
},
}
impl Time {
pub const fn unix_seconds(self) -> Option<u32> {
match self {
Self::SecIndex(_) => None,
Self::Timestamp(t) | Self::LocalTimestamp { timestamp: t, .. } => Some(t),
}
}
pub(crate) fn read(r: &mut Reader<'_>, options: ParseOptions) -> Result<Self> {
let u32_of = |v: u64| u32::try_from(v).map_err(|_| Error::ValueOutOfRange);
if options.bare_time && r.clone().read_tl().is_ok_and(|tl| tl.kind == Kind::Unsigned) {
return Ok(Self::SecIndex(u32_of(r.unsigned()?)?));
}
r.list(2)?;
let choice = r.unsigned()?;
let i16_of = |v: i64| i16::try_from(v).map_err(|_| Error::ValueOutOfRange);
match choice {
1 => Ok(Self::SecIndex(u32_of(r.unsigned()?)?)),
2 => Ok(Self::Timestamp(u32_of(r.unsigned()?)?)),
3 => {
r.list(3)?;
Ok(Self::LocalTimestamp {
timestamp: u32_of(r.unsigned()?)?,
local_offset_minutes: i16_of(r.integer()?)?,
season_offset_minutes: i16_of(r.integer()?)?,
})
}
choice => Err(Error::UnknownChoice { what: "SML_Time", choice }),
}
}
pub(crate) fn read_opt(r: &mut Reader<'_>, options: ParseOptions) -> Result<Option<Self>> {
if r.absent() { Ok(None) } else { Self::read(r, options).map(Some) }
}
pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
w.list(2)?;
match *self {
Self::SecIndex(s) => {
w.unsigned(1, 1)?;
w.unsigned(u64::from(s), 4)
}
Self::Timestamp(t) => {
w.unsigned(2, 1)?;
w.unsigned(u64::from(t), 4)
}
Self::LocalTimestamp { timestamp, local_offset_minutes, season_offset_minutes } => {
w.unsigned(3, 1)?;
w.list(3)?;
w.unsigned(u64::from(timestamp), 4)?;
w.integer(i64::from(local_offset_minutes), 2)?;
w.integer(i64::from(season_offset_minutes), 2)
}
}
}
pub(crate) fn write_opt(t: Option<Self>, w: &mut Writer<'_>) -> Result<()> {
match t {
Some(t) => t.write(w),
None => w.absent(),
}
}
}
fn civil_from_days(days: i64) -> (i64, i64, i64) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
(yoe + era * 400 + i64::from(month <= 2), month, day)
}
fn write_date_time(f: &mut fmt::Formatter<'_>, seconds: i64) -> fmt::Result {
let (days, secs) = (seconds.div_euclid(86_400), seconds.rem_euclid(86_400));
let (y, mo, d) = civil_from_days(days);
write!(f, "{y:04}-{mo:02}-{d:02}T{:02}:{:02}:{:02}", secs / 3600, secs % 3600 / 60, secs % 60)
}
impl fmt::Display for Time {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::SecIndex(s) => write!(f, "secIndex {s} s"),
Self::Timestamp(t) => {
write_date_time(f, i64::from(t))?;
f.write_str("Z")
}
Self::LocalTimestamp { timestamp, local_offset_minutes, season_offset_minutes } => {
let offset = i64::from(local_offset_minutes) + i64::from(season_offset_minutes);
write_date_time(f, i64::from(timestamp) + 60 * offset)?;
let sign = if offset < 0 { '-' } else { '+' };
let offset = offset.unsigned_abs();
write!(f, "{sign}{:02}:{:02}", offset / 60, offset % 60)
}
}
}
}
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
use std::string::ToString;
fn q(mantissa: i128, exponent: i8) -> std::string::String {
Quantity { mantissa, exponent, unit: None }.to_string()
}
#[test]
fn displays_exact_decimals() {
assert_eq!(q(123_456, -1), "12345.6");
assert_eq!(q(5, -3), "0.005");
assert_eq!(q(-42, 0), "-42");
assert_eq!(q(7, 2), "700");
assert_eq!(q(0, -2), "0.00");
assert_eq!(Quantity { mantissa: 15, exponent: -1, unit: Some(Unit::WH) }.to_string(), "1.5 Wh");
}
#[test]
fn every_dlms_unit_code_has_a_symbol() {
for code in 1..=56u8 {
assert!(Unit(code).symbol().is_some_and(|s| !s.is_empty()), "unit {code}");
}
assert_eq!(Unit(57).to_string(), "unit(57)");
assert_eq!(Unit::WH.to_string(), "Wh");
assert_eq!(Quantity { mantissa: 3, exponent: 0, unit: Some(Unit::COUNT) }.to_string(), "3");
}
#[test]
fn corrected_volume_is_its_own_unit() {
assert_ne!(Unit::M3, Unit::M3_CORRECTED);
assert_ne!(Unit::M3_PER_H, Unit::M3_PER_H_CORRECTED);
assert_eq!((Unit::M3_CORRECTED.0, Unit::M3_PER_H_CORRECTED.0), (14, 16));
assert_eq!(Unit::M3.to_string(), Unit::M3_CORRECTED.to_string());
assert_eq!(Unit::M3_PER_H_CORRECTED.to_string(), "m³/h");
}
#[test]
fn integers_widen_exactly() {
assert_eq!(SmlValue::Uint(u64::MAX).as_integer(), Some(18_446_744_073_709_551_615));
assert_eq!(SmlValue::Int(i64::MIN).as_integer(), Some(-9_223_372_036_854_775_808));
assert_eq!(SmlValue::Uint(0).as_integer(), Some(0));
assert_eq!(SmlValue::Bool(true).as_integer(), None);
assert_eq!(SmlValue::Bytes(b"1").as_integer(), None);
assert_eq!(SmlValue::Time(Time::SecIndex(1)).as_integer(), None);
}
#[test]
fn time_displays_as_iso_8601() {
assert_eq!(Time::Timestamp(0).to_string(), "1970-01-01T00:00:00Z");
assert_eq!(Time::Timestamp(951_782_400).to_string(), "2000-02-29T00:00:00Z");
assert_eq!(Time::Timestamp(u32::MAX).to_string(), "2106-02-07T06:28:15Z");
assert_eq!(Time::SecIndex(42).to_string(), "secIndex 42 s");
for (t, date) in [
(4_107_456_000, "2100-02-28"),
(4_107_542_400, "2100-03-01"),
(951_868_800, "2000-03-01"),
(946_598_400, "1999-12-31"),
(3_981_312_000, "2096-02-29"),
(983_404_800, "2001-03-01"),
(4_260_124_800, "2104-12-31"),
] {
assert_eq!(Time::Timestamp(t).to_string(), std::format!("{date}T00:00:00Z"));
}
let utc = Time::LocalTimestamp { timestamp: 0, local_offset_minutes: 0, season_offset_minutes: 0 };
assert_eq!(utc.to_string(), "1970-01-01T00:00:00+00:00");
let summer = Time::LocalTimestamp {
timestamp: 1_719_835_200,
local_offset_minutes: 60,
season_offset_minutes: 60,
};
assert_eq!(summer.to_string(), "2024-07-01T14:00:00+02:00");
let west =
Time::LocalTimestamp { timestamp: 0, local_offset_minutes: -330, season_offset_minutes: 0 };
assert_eq!(west.to_string(), "1969-12-31T18:30:00-05:30");
}
#[test]
fn times_round_trip() {
let opts = ParseOptions::default();
for t in [
Time::SecIndex(7),
Time::Timestamp(1_700_000_000),
Time::LocalTimestamp { timestamp: 1, local_offset_minutes: 60, season_offset_minutes: -60 },
] {
let mut buf = [0u8; 32];
let mut w = Writer::new(&mut buf);
t.write(&mut w).unwrap();
let n = w.position();
assert_eq!(Time::read(&mut Reader::new(&buf[..n]), opts).unwrap(), t);
}
assert_eq!(Time::SecIndex(1).unix_seconds(), None);
assert_eq!(Time::Timestamp(5).unix_seconds(), Some(5));
}
#[test]
fn rescales_without_rounding() {
let e = Quantity { mantissa: 123_456, exponent: -1, unit: None };
assert_eq!(e.to_scale(-3), Some(12_345_600));
assert_eq!(e.to_scale(-1), Some(123_456));
assert_eq!(e.to_scale(0), None, "12345.6 is not a whole number");
let whole = Quantity { mantissa: 1230, exponent: -1, unit: None };
assert_eq!(whole.to_scale(0), Some(123));
assert_eq!(Quantity { mantissa: -1230, ..whole }.to_scale(0), Some(-123));
assert_eq!(Quantity { mantissa: -12_000, ..whole }.to_scale(2), Some(-12), "-1200.0 is -12 hundreds");
assert_eq!(Quantity { mantissa: 1235, ..whole }.to_scale(0), None);
assert_eq!(Quantity { mantissa: 1, exponent: 0, unit: None }.to_scale(-40), None, "overflow");
}
}