1use core::fmt;
2
3use crate::message::ParseOptions;
4use crate::tl::{Kind, Reader, Writer};
5use crate::{Error, Result};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum SmlValue<'a> {
10 Bool(bool),
12 Bytes(&'a [u8]),
14 Int(i64),
16 Uint(u64),
18 Time(Time),
20}
21
22impl<'a> SmlValue<'a> {
23 pub fn as_integer(&self) -> Option<i128> {
34 match *self {
35 Self::Int(v) => Some(i128::from(v)),
36 Self::Uint(v) => Some(i128::from(v)),
37 Self::Bool(_) | Self::Bytes(_) | Self::Time(_) => None,
38 }
39 }
40
41 pub(crate) fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<(Self, usize)> {
44 let tl = r.clone().read_tl()?;
45 Ok(match tl.kind {
46 Kind::Boolean => (Self::Bool(r.boolean()?), 0),
47 Kind::OctetString => (Self::Bytes(r.octet_string()?), 0),
48 Kind::Integer => (Self::Int(r.integer()?), tl.len),
49 Kind::Unsigned => (Self::Uint(r.unsigned()?), tl.len),
50 Kind::List => {
51 r.list(2)?;
52 match r.unsigned()? {
53 1 => (Self::Time(Time::read(r, options)?), 0),
54 choice => return Err(Error::UnknownChoice { what: "SML_Value", choice }),
55 }
56 }
57 })
58 }
59
60 pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
62 match *self {
63 Self::Bool(b) => w.boolean(b),
64 Self::Bytes(b) => w.octet_string(b),
65 Self::Int(v) => w.integer_min(v),
66 Self::Uint(v) => w.unsigned_min(v),
67 Self::Time(t) => {
68 w.list(2)?;
69 w.unsigned(1, 1)?;
70 t.write(w)
71 }
72 }
73 }
74}
75
76#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
78pub struct Unit(pub u8);
79
80impl Unit {
81 pub const CELSIUS: Self = Self(9);
83 #[doc(alias("CUBIC_METRE", "CUBIC_METER"))]
85 pub const M3: Self = Self(13);
86 #[doc(alias("CUBIC_METRE_CORRECTED", "CUBIC_METER_CORRECTED"))]
89 pub const M3_CORRECTED: Self = Self(14);
90 #[doc(alias("CUBIC_METRE_PER_HOUR", "CUBIC_METER_PER_HOUR"))]
92 pub const M3_PER_H: Self = Self(15);
93 #[doc(alias("CUBIC_METRE_PER_HOUR_CORRECTED", "CUBIC_METER_PER_HOUR_CORRECTED"))]
96 pub const M3_PER_H_CORRECTED: Self = Self(16);
97 pub const W: Self = Self(27);
99 pub const VA: Self = Self(28);
101 pub const VAR: Self = Self(29);
103 pub const WH: Self = Self(30);
105 pub const VAH: Self = Self(31);
107 pub const VARH: Self = Self(32);
109 pub const A: Self = Self(33);
111 pub const V: Self = Self(35);
113 pub const HZ: Self = Self(44);
115 pub const PERCENT: Self = Self(56);
117 pub const COUNT: Self = Self(255);
119
120 pub const fn symbol(self) -> Option<&'static str> {
123 Some(match self.0 {
124 1 => "a",
125 2 => "mo",
126 3 => "wk",
127 4 => "d",
128 5 => "h",
129 6 => "min",
130 7 => "s",
131 8 => "°",
132 9 => "°C",
133 10 => "currency",
134 11 => "m",
135 12 => "m/s",
136 13 | 14 => "m³",
137 15 | 16 => "m³/h",
138 17 | 18 => "m³/d",
139 19 => "l",
140 20 => "kg",
141 21 => "N",
142 22 => "Nm",
143 23 => "Pa",
144 24 => "bar",
145 25 => "J",
146 26 => "J/h",
147 27 => "W",
148 28 => "VA",
149 29 => "var",
150 30 => "Wh",
151 31 => "VAh",
152 32 => "varh",
153 33 => "A",
154 34 => "C",
155 35 => "V",
156 36 => "V/m",
157 37 => "F",
158 38 => "Ω",
159 39 => "Ωm²/m",
160 40 => "Wb",
161 41 => "T",
162 42 => "A/m",
163 43 => "H",
164 44 => "Hz",
165 45 => "1/(Wh)",
166 46 => "1/(varh)",
167 47 => "1/(VAh)",
168 48 => "V²h",
169 49 => "A²h",
170 50 => "kg/s",
171 51 => "S",
172 52 => "K",
173 53 => "1/(V²h)",
174 54 => "1/(A²h)",
175 55 => "1/m³",
176 56 => "%",
177 255 => "",
178 _ => return None,
179 })
180 }
181}
182
183impl fmt::Display for Unit {
184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185 match self.symbol() {
186 Some(s) => f.write_str(s),
187 None => write!(f, "unit({})", self.0),
188 }
189 }
190}
191
192#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
198pub struct Quantity {
199 pub mantissa: i128,
201 pub exponent: i8,
203 pub unit: Option<Unit>,
205}
206
207impl Quantity {
208 pub fn to_scale(self, exponent: i8) -> Option<i128> {
211 let diff = i32::from(self.exponent) - i32::from(exponent);
212 if diff >= 0 {
213 10i128.checked_pow(diff.unsigned_abs()).and_then(|p| self.mantissa.checked_mul(p))
214 } else {
215 let p = 10i128.checked_pow(diff.unsigned_abs())?;
216 (self.mantissa % p == 0).then(|| self.mantissa / p)
217 }
218 }
219}
220
221impl fmt::Display for Quantity {
222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223 let mut digits = [0u8; 40];
225 let mut n = self.mantissa.unsigned_abs();
226 let mut len = 0usize;
227 loop {
228 if let Some(slot) = digits.get_mut(len) {
229 *slot = b'0' + (n % 10) as u8;
230 }
231 len += 1;
232 n /= 10;
233 if n == 0 || len >= digits.len() {
234 break;
235 }
236 }
237 let digits = digits.get(..len).unwrap_or(&[]);
238 if self.mantissa < 0 {
239 f.write_str("-")?;
240 }
241 let exp = i32::from(self.exponent);
242 if exp >= 0 {
243 for d in digits.iter().rev() {
244 write!(f, "{}", char::from(*d))?;
245 }
246 for _ in 0..exp {
247 f.write_str("0")?;
248 }
249 } else {
250 let frac = exp.unsigned_abs() as usize;
251 if len <= frac {
252 f.write_str("0.")?;
253 for _ in len..frac {
254 f.write_str("0")?;
255 }
256 for d in digits.iter().rev() {
257 write!(f, "{}", char::from(*d))?;
258 }
259 } else {
260 for (i, d) in digits.iter().rev().enumerate() {
261 if i == len - frac {
262 f.write_str(".")?;
263 }
264 write!(f, "{}", char::from(*d))?;
265 }
266 }
267 }
268 if let Some(unit) = self.unit.filter(|u| u.symbol() != Some("")) {
269 write!(f, " {unit}")?;
270 }
271 Ok(())
272 }
273}
274
275#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
277pub enum Time {
278 SecIndex(u32),
280 Timestamp(u32),
282 LocalTimestamp {
284 timestamp: u32,
286 local_offset_minutes: i16,
288 season_offset_minutes: i16,
290 },
291}
292
293impl Time {
294 pub const fn unix_seconds(self) -> Option<u32> {
297 match self {
298 Self::SecIndex(_) => None,
299 Self::Timestamp(t) | Self::LocalTimestamp { timestamp: t, .. } => Some(t),
300 }
301 }
302
303 pub(crate) fn read(r: &mut Reader<'_>, options: ParseOptions) -> Result<Self> {
304 let u32_of = |v: u64| u32::try_from(v).map_err(|_| Error::ValueOutOfRange);
305 if options.bare_time && r.clone().read_tl().is_ok_and(|tl| tl.kind == Kind::Unsigned) {
307 return Ok(Self::SecIndex(u32_of(r.unsigned()?)?));
308 }
309 r.list(2)?;
310 let choice = r.unsigned()?;
311 let i16_of = |v: i64| i16::try_from(v).map_err(|_| Error::ValueOutOfRange);
312 match choice {
313 1 => Ok(Self::SecIndex(u32_of(r.unsigned()?)?)),
314 2 => Ok(Self::Timestamp(u32_of(r.unsigned()?)?)),
315 3 => {
316 r.list(3)?;
317 Ok(Self::LocalTimestamp {
318 timestamp: u32_of(r.unsigned()?)?,
319 local_offset_minutes: i16_of(r.integer()?)?,
320 season_offset_minutes: i16_of(r.integer()?)?,
321 })
322 }
323 choice => Err(Error::UnknownChoice { what: "SML_Time", choice }),
324 }
325 }
326
327 pub(crate) fn read_opt(r: &mut Reader<'_>, options: ParseOptions) -> Result<Option<Self>> {
328 if r.absent() { Ok(None) } else { Self::read(r, options).map(Some) }
329 }
330
331 pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
333 w.list(2)?;
334 match *self {
335 Self::SecIndex(s) => {
336 w.unsigned(1, 1)?;
337 w.unsigned(u64::from(s), 4)
338 }
339 Self::Timestamp(t) => {
340 w.unsigned(2, 1)?;
341 w.unsigned(u64::from(t), 4)
342 }
343 Self::LocalTimestamp { timestamp, local_offset_minutes, season_offset_minutes } => {
344 w.unsigned(3, 1)?;
345 w.list(3)?;
346 w.unsigned(u64::from(timestamp), 4)?;
347 w.integer(i64::from(local_offset_minutes), 2)?;
348 w.integer(i64::from(season_offset_minutes), 2)
349 }
350 }
351 }
352
353 pub(crate) fn write_opt(t: Option<Self>, w: &mut Writer<'_>) -> Result<()> {
354 match t {
355 Some(t) => t.write(w),
356 None => w.absent(),
357 }
358 }
359}
360
361fn civil_from_days(days: i64) -> (i64, i64, i64) {
364 let z = days + 719_468;
365 let era = z.div_euclid(146_097);
366 let doe = z.rem_euclid(146_097);
367 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
368 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
369 let mp = (5 * doy + 2) / 153;
370 let day = doy - (153 * mp + 2) / 5 + 1;
371 let month = if mp < 10 { mp + 3 } else { mp - 9 };
372 (yoe + era * 400 + i64::from(month <= 2), month, day)
373}
374
375fn write_date_time(f: &mut fmt::Formatter<'_>, seconds: i64) -> fmt::Result {
377 let (days, secs) = (seconds.div_euclid(86_400), seconds.rem_euclid(86_400));
378 let (y, mo, d) = civil_from_days(days);
379 write!(f, "{y:04}-{mo:02}-{d:02}T{:02}:{:02}:{:02}", secs / 3600, secs % 3600 / 60, secs % 60)
380}
381
382impl fmt::Display for Time {
393 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394 match *self {
395 Self::SecIndex(s) => write!(f, "secIndex {s} s"),
396 Self::Timestamp(t) => {
397 write_date_time(f, i64::from(t))?;
398 f.write_str("Z")
399 }
400 Self::LocalTimestamp { timestamp, local_offset_minutes, season_offset_minutes } => {
401 let offset = i64::from(local_offset_minutes) + i64::from(season_offset_minutes);
402 write_date_time(f, i64::from(timestamp) + 60 * offset)?;
403 let sign = if offset < 0 { '-' } else { '+' };
404 let offset = offset.unsigned_abs();
405 write!(f, "{sign}{:02}:{:02}", offset / 60, offset % 60)
406 }
407 }
408 }
409}
410
411#[cfg(test)]
412mod tests {
413 extern crate std;
414 use super::*;
415 use std::string::ToString;
416
417 fn q(mantissa: i128, exponent: i8) -> std::string::String {
418 Quantity { mantissa, exponent, unit: None }.to_string()
419 }
420
421 #[test]
422 fn displays_exact_decimals() {
423 assert_eq!(q(123_456, -1), "12345.6");
424 assert_eq!(q(5, -3), "0.005");
425 assert_eq!(q(-42, 0), "-42");
426 assert_eq!(q(7, 2), "700");
427 assert_eq!(q(0, -2), "0.00");
428 assert_eq!(Quantity { mantissa: 15, exponent: -1, unit: Some(Unit::WH) }.to_string(), "1.5 Wh");
429 }
430
431 #[test]
432 fn every_dlms_unit_code_has_a_symbol() {
433 for code in 1..=56u8 {
434 assert!(Unit(code).symbol().is_some_and(|s| !s.is_empty()), "unit {code}");
435 }
436 assert_eq!(Unit(57).to_string(), "unit(57)");
437 assert_eq!(Unit::WH.to_string(), "Wh");
438 assert_eq!(Quantity { mantissa: 3, exponent: 0, unit: Some(Unit::COUNT) }.to_string(), "3");
439 }
440
441 #[test]
443 fn corrected_volume_is_its_own_unit() {
444 assert_ne!(Unit::M3, Unit::M3_CORRECTED);
445 assert_ne!(Unit::M3_PER_H, Unit::M3_PER_H_CORRECTED);
446 assert_eq!((Unit::M3_CORRECTED.0, Unit::M3_PER_H_CORRECTED.0), (14, 16));
447 assert_eq!(Unit::M3.to_string(), Unit::M3_CORRECTED.to_string());
448 assert_eq!(Unit::M3_PER_H_CORRECTED.to_string(), "m³/h");
449 }
450
451 #[test]
453 fn integers_widen_exactly() {
454 assert_eq!(SmlValue::Uint(u64::MAX).as_integer(), Some(18_446_744_073_709_551_615));
455 assert_eq!(SmlValue::Int(i64::MIN).as_integer(), Some(-9_223_372_036_854_775_808));
456 assert_eq!(SmlValue::Uint(0).as_integer(), Some(0));
457 assert_eq!(SmlValue::Bool(true).as_integer(), None);
458 assert_eq!(SmlValue::Bytes(b"1").as_integer(), None);
459 assert_eq!(SmlValue::Time(Time::SecIndex(1)).as_integer(), None);
460 }
461
462 #[test]
463 fn time_displays_as_iso_8601() {
464 assert_eq!(Time::Timestamp(0).to_string(), "1970-01-01T00:00:00Z");
465 assert_eq!(Time::Timestamp(951_782_400).to_string(), "2000-02-29T00:00:00Z");
466 assert_eq!(Time::Timestamp(u32::MAX).to_string(), "2106-02-07T06:28:15Z");
467 assert_eq!(Time::SecIndex(42).to_string(), "secIndex 42 s");
468 for (t, date) in [
471 (4_107_456_000, "2100-02-28"),
472 (4_107_542_400, "2100-03-01"),
473 (951_868_800, "2000-03-01"),
474 (946_598_400, "1999-12-31"),
475 (3_981_312_000, "2096-02-29"),
476 (983_404_800, "2001-03-01"),
477 (4_260_124_800, "2104-12-31"),
478 ] {
479 assert_eq!(Time::Timestamp(t).to_string(), std::format!("{date}T00:00:00Z"));
480 }
481 let utc = Time::LocalTimestamp { timestamp: 0, local_offset_minutes: 0, season_offset_minutes: 0 };
482 assert_eq!(utc.to_string(), "1970-01-01T00:00:00+00:00");
483 let summer = Time::LocalTimestamp {
484 timestamp: 1_719_835_200,
485 local_offset_minutes: 60,
486 season_offset_minutes: 60,
487 };
488 assert_eq!(summer.to_string(), "2024-07-01T14:00:00+02:00");
489 let west =
490 Time::LocalTimestamp { timestamp: 0, local_offset_minutes: -330, season_offset_minutes: 0 };
491 assert_eq!(west.to_string(), "1969-12-31T18:30:00-05:30");
492 }
493
494 #[test]
495 fn times_round_trip() {
496 let opts = ParseOptions::default();
497 for t in [
498 Time::SecIndex(7),
499 Time::Timestamp(1_700_000_000),
500 Time::LocalTimestamp { timestamp: 1, local_offset_minutes: 60, season_offset_minutes: -60 },
501 ] {
502 let mut buf = [0u8; 32];
503 let mut w = Writer::new(&mut buf);
504 t.write(&mut w).unwrap();
505 let n = w.position();
506 assert_eq!(Time::read(&mut Reader::new(&buf[..n]), opts).unwrap(), t);
507 }
508 assert_eq!(Time::SecIndex(1).unix_seconds(), None);
509 assert_eq!(Time::Timestamp(5).unix_seconds(), Some(5));
510 }
511
512 #[test]
513 fn rescales_without_rounding() {
514 let e = Quantity { mantissa: 123_456, exponent: -1, unit: None };
515 assert_eq!(e.to_scale(-3), Some(12_345_600));
516 assert_eq!(e.to_scale(-1), Some(123_456));
517 assert_eq!(e.to_scale(0), None, "12345.6 is not a whole number");
518 let whole = Quantity { mantissa: 1230, exponent: -1, unit: None };
519 assert_eq!(whole.to_scale(0), Some(123));
520 assert_eq!(Quantity { mantissa: -1230, ..whole }.to_scale(0), Some(-123));
521 assert_eq!(Quantity { mantissa: -12_000, ..whole }.to_scale(2), Some(-12), "-1200.0 is -12 hundreds");
522 assert_eq!(Quantity { mantissa: 1235, ..whole }.to_scale(0), None);
523 assert_eq!(Quantity { mantissa: 1, exponent: 0, unit: None }.to_scale(-40), None, "overflow");
524 }
525}