Skip to main content

sml_kit/
message.rs

1//! SML messages: `SML_Message`, the bodies a meter and a client exchange, and the options
2//! that decide how strictly they are read.
3//!
4//! ```text
5//! SML_Message ::= List(6) {
6//!     transactionId  Octet String
7//!     groupNo        Unsigned8
8//!     abortOnError   Unsigned8
9//!     messageBody    List(2) { tag Unsigned32, body … }
10//!     crc16          Unsigned16
11//!     endOfSmlMsg    0x00
12//! }
13//! ```
14//!
15//! A meter's push telegram is usually three messages: an `OpenResponse`, a
16//! `GetListResponse` with the readings, and a `CloseResponse`. A client on the LMN sends
17//! `OpenRequest`, `GetListRequest` and `CloseRequest`. Bodies this crate does not type (the COSEM
18//! bodies) are kept as [`Body::Other`] with their raw bytes.
19
20use core::fmt;
21
22use crate::crc::{CrcCheck, kermit, x25};
23use crate::seq::{Ctx, Element, Seq};
24use crate::tl::{Kind, Reader, Writer};
25use crate::tree::{NameList, PeriodEntries, Tree};
26use crate::value::{Quantity, SmlValue, Time, Unit};
27use crate::{Error, GetProfilePackResponse, Obis, Result, ServerId};
28
29/// Message body tags (`SML_MessageBody` choice).
30pub mod tag {
31    /// `SML_PublicOpen.Req`.
32    pub const OPEN_REQUEST: u32 = 0x0000_0100;
33    /// `SML_PublicOpen.Res`.
34    pub const OPEN_RESPONSE: u32 = 0x0000_0101;
35    /// `SML_PublicClose.Req`.
36    pub const CLOSE_REQUEST: u32 = 0x0000_0200;
37    /// `SML_PublicClose.Res`.
38    pub const CLOSE_RESPONSE: u32 = 0x0000_0201;
39    /// `SML_GetProfilePack.Req`.
40    pub const GET_PROFILE_PACK_REQUEST: u32 = 0x0000_0300;
41    /// `SML_GetProfilePack.Res`.
42    pub const GET_PROFILE_PACK_RESPONSE: u32 = 0x0000_0301;
43    /// `SML_GetProfileList.Req`.
44    pub const GET_PROFILE_LIST_REQUEST: u32 = 0x0000_0400;
45    /// `SML_GetProfileList.Res`.
46    pub const GET_PROFILE_LIST_RESPONSE: u32 = 0x0000_0401;
47    /// `SML_GetProcParameter.Req`.
48    pub const GET_PROC_PARAMETER_REQUEST: u32 = 0x0000_0500;
49    /// `SML_GetProcParameter.Res`.
50    pub const GET_PROC_PARAMETER_RESPONSE: u32 = 0x0000_0501;
51    /// `SML_SetProcParameter.Req`.
52    pub const SET_PROC_PARAMETER_REQUEST: u32 = 0x0000_0600;
53    /// `SML_GetList.Req`.
54    pub const GET_LIST_REQUEST: u32 = 0x0000_0700;
55    /// `SML_GetList.Res`.
56    pub const GET_LIST_RESPONSE: u32 = 0x0000_0701;
57    /// `SML_Attention.Res`.
58    pub const ATTENTION_RESPONSE: u32 = 0x0000_FF01;
59}
60
61/// How messages are read: how strictly the CRC is checked, and which named meter
62/// deviations are tolerated.
63///
64/// The default is strict: the specification, nothing else. A meter that deviates is read
65/// by naming the deviation, so it stays visible:
66///
67/// ```
68/// use sml_kit::{CrcCheck, ParseOptions};
69///
70/// let strict = ParseOptions::default();
71/// let holley = ParseOptions::lenient();                 // KERMIT CRC, time without choice
72/// let dzg = ParseOptions::default().with_dzg_power(true); // DZG DVS74 sign bug
73/// let damaged = ParseOptions { crc: CrcCheck::Off, ..ParseOptions::default() };
74/// # let _ = (strict, holley, dzg, damaged);
75/// ```
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
77pub struct ParseOptions {
78    /// How each message's CRC is checked. [`CrcCheck::Strict`] by default.
79    pub crc: CrcCheck,
80    /// Accept a bare `Unsigned` where an `SML_Time` belongs and read it as a seconds
81    /// index. Some Holley DTZ541 and DDZ285 omit the time's choice tag. Off by default.
82    pub bare_time: bool,
83    /// Correct the DZG DVS74 power sign bug. Off by default, and not part of
84    /// [`ParseOptions::lenient`], because it changes values.
85    ///
86    /// Affected DZG meters send a positive power of 327.68 W or more (scaler −2) as a
87    /// short *signed* integer, so 356.24 W reads −299.12 W. With this set, a negative
88    /// `Integer` of 1–3 bytes for active power (`1-0:16.7.0`, `36.7.0`, `56.7.0`,
89    /// `76.7.0`) is read as the unsigned number of the same bytes, in lists whose server
90    /// ID names manufacturer `DZG`. Affected meters send genuine negatives in 4 bytes or
91    /// more, which stay negative.
92    ///
93    /// Only set it for a meter that shows the bug: a DZG meter with fixed firmware may
94    /// send a genuine negative power in 2 bytes, which this would corrupt.
95    pub dzg_power: bool,
96}
97
98impl ParseOptions {
99    /// Every allowance that does not change a value: [`CrcCheck::Lenient`] (KERMIT or
100    /// either byte order) and [`ParseOptions::bare_time`].
101    pub const fn lenient() -> Self {
102        Self { crc: CrcCheck::Lenient, bare_time: true, dzg_power: false }
103    }
104
105    /// These options with the DZG power correction set or cleared.
106    #[must_use]
107    pub const fn with_dzg_power(mut self, on: bool) -> Self {
108        self.dzg_power = on;
109        self
110    }
111}
112
113/// One SML message.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct Message<'a> {
116    /// Identifies a request and its response.
117    pub transaction_id: &'a [u8],
118    /// Groups messages that belong together.
119    pub group_no: u8,
120    /// What the receiver does when this message fails (0 = continue).
121    pub abort_on_error: u8,
122    /// The message body.
123    pub body: Body<'a>,
124}
125
126/// A message body.
127#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128#[non_exhaustive]
129pub enum Body<'a> {
130    /// A client opens an SML file.
131    OpenRequest(OpenRequest<'a>),
132    /// The device opens an SML file.
133    OpenResponse(OpenResponse<'a>),
134    /// A client closes an SML file.
135    CloseRequest(CloseRequest<'a>),
136    /// The device closes an SML file.
137    CloseResponse(CloseResponse<'a>),
138    /// A client asks for a list of values.
139    GetListRequest(GetListRequest<'a>),
140    /// Readings: a list of named values.
141    GetListResponse(GetListResponse<'a>),
142    /// An error or status code from the device. Also the answer to a set request.
143    Attention(Attention<'a>),
144    /// A client asks for parameters.
145    GetProcParameterRequest(GetProcParameterRequest<'a>),
146    /// Parameters: a tree of named values.
147    GetProcParameterResponse(GetProcParameterResponse<'a>),
148    /// A client sets parameters. The device answers with an [`Attention`].
149    SetProcParameterRequest(SetProcParameterRequest<'a>),
150    /// A client asks for a profile as one packed response (`SML_GetProfilePack.Req`).
151    GetProfilePackRequest(GetProfileRequest<'a>),
152    /// A client asks for a profile as a list of periods (`SML_GetProfileList.Req`).
153    GetProfileListRequest(GetProfileRequest<'a>),
154    /// One period of a profile, e.g. one logbook entry.
155    GetProfileListResponse(GetProfileListResponse<'a>),
156    /// A whole profile: column headers once, then rows of values.
157    GetProfilePackResponse(GetProfilePackResponse<'a>),
158    /// A body this crate does not type, with its raw bytes: the COSEM bodies, for which
159    /// no real use was found.
160    Other {
161        /// The body's tag.
162        tag: u32,
163        /// The body's encoded value, TL bytes included.
164        raw: &'a [u8],
165    },
166}
167
168/// Formats an optional secret without its content.
169struct Redacted(bool);
170
171impl fmt::Debug for Redacted {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        f.write_str(if self.0 { "Some(<redacted>)" } else { "None" })
174    }
175}
176
177/// `SML_PublicOpen.Req`. `Debug` does not print the password.
178#[derive(Clone, Copy, PartialEq, Eq)]
179pub struct OpenRequest<'a> {
180    /// The code page, when not the default (ISO 8859-15).
181    pub codepage: Option<&'a [u8]>,
182    /// The client opening the file.
183    pub client_id: &'a [u8],
184    /// The file identifier the responses repeat.
185    pub req_file_id: &'a [u8],
186    /// The device addressed, when there is more than one.
187    pub server_id: Option<ServerId<'a>>,
188    /// The user name, when the device requires one.
189    pub username: Option<&'a [u8]>,
190    /// The password, when the device requires one.
191    pub password: Option<&'a [u8]>,
192    /// The SML version, when stated (absent means version 1).
193    pub sml_version: Option<u8>,
194}
195
196impl fmt::Debug for OpenRequest<'_> {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        f.debug_struct("OpenRequest")
199            .field("codepage", &self.codepage)
200            .field("client_id", &self.client_id)
201            .field("req_file_id", &self.req_file_id)
202            .field("server_id", &self.server_id)
203            .field("username", &self.username)
204            .field("password", &Redacted(self.password.is_some()))
205            .field("sml_version", &self.sml_version)
206            .finish()
207    }
208}
209
210/// `SML_PublicOpen.Res`.
211#[derive(Clone, Copy, Debug, PartialEq, Eq)]
212pub struct OpenResponse<'a> {
213    /// The code page, when not the default (ISO 8859-15).
214    pub codepage: Option<&'a [u8]>,
215    /// The client the response is for.
216    pub client_id: Option<&'a [u8]>,
217    /// The file identifier from the request.
218    pub req_file_id: &'a [u8],
219    /// The device that answered.
220    pub server_id: ServerId<'a>,
221    /// The device's time reference.
222    pub ref_time: Option<Time>,
223    /// The SML version, when stated.
224    pub sml_version: Option<u8>,
225}
226
227/// `SML_PublicClose.Req`.
228#[derive(Clone, Copy, Debug, PartialEq, Eq)]
229pub struct CloseRequest<'a> {
230    /// A signature over the whole file, when the client signs. Not verified.
231    pub global_signature: Option<&'a [u8]>,
232}
233
234/// `SML_PublicClose.Res`.
235#[derive(Clone, Copy, Debug, PartialEq, Eq)]
236pub struct CloseResponse<'a> {
237    /// A signature over the whole file, when the device signs. **Not verified** by this
238    /// crate.
239    pub global_signature: Option<&'a [u8]>,
240}
241
242/// `SML_GetList.Req`. `Debug` does not print the password.
243#[derive(Clone, Copy, PartialEq, Eq)]
244pub struct GetListRequest<'a> {
245    /// The client asking.
246    pub client_id: &'a [u8],
247    /// The device addressed, when there is more than one.
248    pub server_id: Option<ServerId<'a>>,
249    /// The user name, when the device requires one.
250    pub username: Option<&'a [u8]>,
251    /// The password, when the device requires one.
252    pub password: Option<&'a [u8]>,
253    /// The list asked for, an OBIS code; absent for the default list.
254    pub list_name: Option<&'a [u8]>,
255}
256
257impl fmt::Debug for GetListRequest<'_> {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.debug_struct("GetListRequest")
260            .field("client_id", &self.client_id)
261            .field("server_id", &self.server_id)
262            .field("username", &self.username)
263            .field("password", &Redacted(self.password.is_some()))
264            .field("list_name", &self.list_name)
265            .finish()
266    }
267}
268
269/// `SML_Attention.Res`.
270#[derive(Clone, Copy, Debug, PartialEq, Eq)]
271pub struct Attention<'a> {
272    /// The device that answered.
273    pub server_id: ServerId<'a>,
274    /// The attention number, see [`attention`](crate::attention).
275    pub number: &'a [u8],
276    /// A human-readable message, when the device sends one.
277    pub message: Option<&'a [u8]>,
278    /// `attentionDetails`, an `SML_Tree`, as its raw bytes.
279    pub details: Option<&'a [u8]>,
280}
281
282impl Attention<'_> {
283    /// What the attention number means, for the standard numbers.
284    pub fn description(&self) -> Option<&'static str> {
285        crate::attention::describe(self.number)
286    }
287}
288
289/// `SML_GetProcParameter.Req`. `Debug` does not print the password.
290#[derive(Clone, Copy, PartialEq, Eq)]
291pub struct GetProcParameterRequest<'a> {
292    /// The device addressed, when there is more than one.
293    pub server_id: Option<ServerId<'a>>,
294    /// The user name, when the device requires one.
295    pub username: Option<&'a [u8]>,
296    /// The password, when the device requires one.
297    pub password: Option<&'a [u8]>,
298    /// The path to the parameter, root first (e.g. `[81 81 C7 82 01 FF]`).
299    pub tree_path: NameList<'a>,
300    /// One attribute of the parameter, when only that one is asked for.
301    pub attribute: Option<&'a [u8]>,
302}
303
304impl fmt::Debug for GetProcParameterRequest<'_> {
305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306        f.debug_struct("GetProcParameterRequest")
307            .field("server_id", &self.server_id)
308            .field("username", &self.username)
309            .field("password", &Redacted(self.password.is_some()))
310            .field("tree_path", &self.tree_path)
311            .field("attribute", &self.attribute)
312            .finish()
313    }
314}
315
316/// `SML_GetProcParameter.Res`.
317#[derive(Clone, Copy, Debug, PartialEq, Eq)]
318pub struct GetProcParameterResponse<'a> {
319    /// The device that answered.
320    pub server_id: ServerId<'a>,
321    /// The path asked for.
322    pub tree_path: NameList<'a>,
323    /// The parameters.
324    pub tree: Tree<'a>,
325}
326
327/// `SML_SetProcParameter.Req`. `Debug` does not print the password.
328///
329/// Writes change the meter: tariff, INFO interface, PIN and its protection, tamper
330/// detection (FNN Lastenheft EDL Tab. 19). The meter decides whether the request is
331/// allowed and answers with an [`Attention`].
332#[derive(Clone, Copy, PartialEq, Eq)]
333pub struct SetProcParameterRequest<'a> {
334    /// The device addressed, when there is more than one.
335    pub server_id: Option<ServerId<'a>>,
336    /// The user name, when the device requires one.
337    pub username: Option<&'a [u8]>,
338    /// The password, when the device requires one.
339    pub password: Option<&'a [u8]>,
340    /// The path to the parameter, root first.
341    pub tree_path: NameList<'a>,
342    /// The new values.
343    pub tree: Tree<'a>,
344}
345
346impl fmt::Debug for SetProcParameterRequest<'_> {
347    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348        f.debug_struct("SetProcParameterRequest")
349            .field("server_id", &self.server_id)
350            .field("username", &self.username)
351            .field("password", &Redacted(self.password.is_some()))
352            .field("tree_path", &self.tree_path)
353            .field("tree", &self.tree)
354            .finish()
355    }
356}
357
358/// `SML_GetProfilePack.Req` and `SML_GetProfileList.Req`, which share one grammar.
359/// `Debug` does not print the password.
360#[derive(Clone, Copy, PartialEq, Eq)]
361pub struct GetProfileRequest<'a> {
362    /// The device addressed, when there is more than one.
363    pub server_id: Option<ServerId<'a>>,
364    /// The user name, when the device requires one.
365    pub username: Option<&'a [u8]>,
366    /// The password, when the device requires one.
367    pub password: Option<&'a [u8]>,
368    /// Whether raw data is wanted too.
369    pub with_rawdata: Option<bool>,
370    /// The first period (absent: from the oldest).
371    pub begin_time: Option<Time>,
372    /// The last period (absent: up to the newest).
373    pub end_time: Option<Time>,
374    /// The profile, e.g. the EDL logbook `[81 81 C7 89 E1 FF]`.
375    pub tree_path: NameList<'a>,
376    /// The objects wanted, when not all.
377    pub objects: Option<NameList<'a>>,
378    /// Further details, device specific.
379    pub details: Option<Tree<'a>>,
380}
381
382impl fmt::Debug for GetProfileRequest<'_> {
383    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384        f.debug_struct("GetProfileRequest")
385            .field("server_id", &self.server_id)
386            .field("username", &self.username)
387            .field("password", &Redacted(self.password.is_some()))
388            .field("with_rawdata", &self.with_rawdata)
389            .field("begin_time", &self.begin_time)
390            .field("end_time", &self.end_time)
391            .field("tree_path", &self.tree_path)
392            .field("objects", &self.objects)
393            .field("details", &self.details)
394            .finish()
395    }
396}
397
398/// `SML_GetProfileList.Res`: one period of a profile.
399#[derive(Clone, Copy, Debug, PartialEq, Eq)]
400pub struct GetProfileListResponse<'a> {
401    /// The device that answered.
402    pub server_id: ServerId<'a>,
403    /// The device's time when it answered.
404    pub act_time: Time,
405    /// The registration period in seconds (0: event driven).
406    pub reg_period: u32,
407    /// The profile.
408    pub tree_path: NameList<'a>,
409    /// The period's time.
410    pub val_time: Time,
411    /// Status bits of the period.
412    pub status: u64,
413    /// The period's values.
414    pub entries: PeriodEntries<'a>,
415    /// Raw data, when asked for.
416    pub rawdata: Option<&'a [u8]>,
417    /// A signature over the period, when the device signs. **Not verified** by this crate.
418    pub period_signature: Option<&'a [u8]>,
419}
420
421/// `SML_GetList.Res`: the readings.
422#[derive(Clone, Copy, Debug, PartialEq, Eq)]
423pub struct GetListResponse<'a> {
424    /// The client the response is for.
425    pub client_id: Option<&'a [u8]>,
426    /// The device that answered, usually the meter's server ID.
427    pub server_id: ServerId<'a>,
428    /// The list's name, an OBIS code when present.
429    pub list_name: Option<&'a [u8]>,
430    /// The sensor's time when the values were captured.
431    pub act_sensor_time: Option<Time>,
432    /// The entries. Parsed lazily: iterate to read them.
433    pub entries: ListEntries<'a>,
434    /// A signature over the list, when the device signs. **Not verified** by this crate.
435    pub list_signature: Option<&'a [u8]>,
436    /// The gateway's time, when a gateway relayed the list.
437    pub act_gateway_time: Option<Time>,
438}
439
440impl<'a> GetListResponse<'a> {
441    /// The first entry named `obis`, if any.
442    pub fn get(&self, obis: Obis) -> Option<ListEntry<'a>> {
443        self.entries.iter().filter_map(core::result::Result::ok).find(|e| e.obis == obis)
444    }
445
446    /// The exact value of the first entry named `obis`, when it is numeric.
447    pub fn quantity(&self, obis: Obis) -> Option<Quantity> {
448        self.get(obis).and_then(|e| e.quantity())
449    }
450}
451
452/// The entries of a [`GetListResponse`]: parsed one at a time when decoded, or a slice
453/// when built for writing.
454pub type ListEntries<'a> = Seq<'a, ListEntry<'a>>;
455
456/// `SML_ListEntry`: one named value.
457#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
458pub struct ListEntry<'a> {
459    /// What the value is.
460    pub obis: Obis,
461    /// Device-specific status bits.
462    pub status: Option<u64>,
463    /// When the value was captured.
464    pub val_time: Option<Time>,
465    /// The unit of a numeric value.
466    pub unit: Option<Unit>,
467    /// The decimal exponent of a numeric value.
468    pub scaler: Option<i8>,
469    /// The value.
470    pub value: SmlValue<'a>,
471    /// A signature over the value, when the device signs. **Not verified** by this crate.
472    pub value_signature: Option<&'a [u8]>,
473}
474
475impl<'a> ListEntry<'a> {
476    /// A signed numeric entry (`Integer` on the wire): `value × 10^scaler` in `unit`, no
477    /// status, time or signature. Power is signed; for energy registers see [`unsigned`].
478    ///
479    /// Set the other fields with struct update syntax:
480    /// `ListEntry { status: Some(0x0104), ..ListEntry::number(..) }`.
481    ///
482    /// [`unsigned`]: Self::unsigned
483    pub const fn number(obis: Obis, unit: Unit, scaler: i8, value: i64) -> Self {
484        Self::numeric(obis, unit, scaler, SmlValue::Int(value))
485    }
486
487    /// An unsigned numeric entry (`Unsigned` on the wire), the encoding most meters use
488    /// for energy registers; otherwise like [`number`](Self::number).
489    ///
490    /// ```
491    /// use sml_kit::{ListEntry, Obis, SmlValue, Unit};
492    ///
493    /// const IMPORT: ListEntry<'static> = ListEntry::unsigned(Obis::ENERGY_IMPORT, Unit::WH, -1, 123_456_789);
494    /// assert_eq!(IMPORT.value, SmlValue::Uint(123_456_789));
495    /// assert_eq!(IMPORT.quantity().unwrap().to_string(), "12345678.9 Wh");
496    /// ```
497    pub const fn unsigned(obis: Obis, unit: Unit, scaler: i8, value: u64) -> Self {
498        Self::numeric(obis, unit, scaler, SmlValue::Uint(value))
499    }
500
501    const fn numeric(obis: Obis, unit: Unit, scaler: i8, value: SmlValue<'a>) -> Self {
502        Self {
503            obis,
504            status: None,
505            val_time: None,
506            unit: Some(unit),
507            scaler: Some(scaler),
508            value,
509            value_signature: None,
510        }
511    }
512
513    /// A byte-string entry (identifiers, text).
514    pub const fn bytes(obis: Obis, value: &'a [u8]) -> Self {
515        Self {
516            obis,
517            status: None,
518            val_time: None,
519            unit: None,
520            scaler: None,
521            value: SmlValue::Bytes(value),
522            value_signature: None,
523        }
524    }
525}
526
527impl<'a> Element<'a> for ListEntry<'a> {
528    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
529        let (options, dzg) = (ctx.options, ctx.dzg);
530        r.list(7)?;
531        let obis = Obis::from_bytes(r.octet_string()?)?;
532        let status = r.opt_unsigned()?;
533        let val_time = Time::read_opt(r, options)?;
534        let unit = r
535            .opt_unsigned()?
536            .map(|u| u8::try_from(u).map(Unit))
537            .transpose()
538            .map_err(|_| Error::ValueOutOfRange)?;
539        let scaler = r.opt_integer()?.map(i8::try_from).transpose().map_err(|_| Error::ValueOutOfRange)?;
540        let (mut value, width) = SmlValue::read(r, options)?;
541        if dzg && obis.is_active_power() {
542            value = dzg_unsigned(value, width);
543        }
544        let value_signature = r.opt_octet_string()?;
545        Ok(Self { obis, status, val_time, unit, scaler, value, value_signature })
546    }
547
548    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
549        ListEntry::write(self, w)
550    }
551}
552
553impl ListEntry<'_> {
554    /// Write the entry: status and value in the smallest width that holds them.
555    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
556        w.list(7)?;
557        w.octet_string(&self.obis.0)?;
558        match self.status {
559            Some(s) => w.unsigned_min(s)?,
560            None => w.absent()?,
561        }
562        Time::write_opt(self.val_time, w)?;
563        match self.unit {
564            Some(u) => w.unsigned(u64::from(u.0), 1)?,
565            None => w.absent()?,
566        }
567        match self.scaler {
568            Some(s) => w.integer(i64::from(s), 1)?,
569            None => w.absent()?,
570        }
571        self.value.write(w)?;
572        w.opt_octet_string(self.value_signature)
573    }
574
575    /// The value as an exact [`Quantity`], when it is numeric.
576    pub fn quantity(&self) -> Option<Quantity> {
577        let mantissa = self.value.as_integer()?;
578        Some(Quantity { mantissa, exponent: self.scaler.unwrap_or(0), unit: self.unit })
579    }
580}
581
582/// The DZG DVS74 correction: a negative `Integer` of 1–3 bytes is the unsigned number of
583/// the same bytes.
584fn dzg_unsigned(value: SmlValue<'_>, width: usize) -> SmlValue<'_> {
585    match value {
586        SmlValue::Int(v) if v < 0 && (1..=3).contains(&width) => {
587            let bits = u64::from_be_bytes(v.to_be_bytes());
588            SmlValue::Uint(bits & ((1u64 << (8 * width)) - 1))
589        }
590        other => other,
591    }
592}
593
594impl<'a> Message<'a> {
595    /// Parse one message at the reader's position and check its CRC.
596    pub fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<Self> {
597        let start = r.position();
598        r.list(6)?;
599        let transaction_id = r.octet_string()?;
600        let group_no = u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
601        let abort_on_error = u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
602        let body = Body::read(r, options)?;
603        let crc_end = r.position();
604        // An Unsigned16 may drop its leading zero byte (ISKRA MT691 does), never add one.
605        if r.clone().read_tl().is_ok_and(|tl| tl.kind == Kind::Unsigned && tl.len > 2) {
606            return Err(Error::InvalidLength);
607        }
608        let found = u16::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
609        let covered = r.slice(start, crc_end)?;
610        let computed = x25(covered);
611        let accepted = match options.crc {
612            CrcCheck::Lenient => options.crc.accepts(computed, kermit(covered), found),
613            check => check.accepts(computed, 0, found),
614        };
615        if !accepted {
616            return Err(Error::MessageCrc { computed, found });
617        }
618        r.end_of_message()?;
619        Ok(Self { transaction_id, group_no, abort_on_error, body })
620    }
621
622    /// Write the message with its CRC (CRC-16/X-25, low byte first) and end-of-message
623    /// byte.
624    ///
625    /// Reading the result yields an equal message. The bytes may differ from the ones a
626    /// message was decoded from, because integer widths are not kept. An empty optional
627    /// octet string (`Some(&[])`) is written as `01`, which SML reads as absent: the two
628    /// cannot be told apart on the wire.
629    ///
630    /// Raw parts (`Attention::details`, `Body::Other`) must each be exactly one encoded
631    /// element, or the result is [`Error::InvalidLength`] and nothing is written that
632    /// would carry a valid CRC over a broken structure.
633    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
634        let start = w.position();
635        w.list(6)?;
636        w.octet_string(self.transaction_id)?;
637        w.unsigned(u64::from(self.group_no), 1)?;
638        w.unsigned(u64::from(self.abort_on_error), 1)?;
639        self.body.write(w)?;
640        let crc = x25(w.written().get(start..).unwrap_or(&[]));
641        w.unsigned(u64::from(crc.swap_bytes()), 2)?;
642        w.end_of_message()
643    }
644}
645
646fn read_u8(r: &mut Reader<'_>) -> Result<Option<u8>> {
647    r.opt_unsigned()?.map(u8::try_from).transpose().map_err(|_| Error::ValueOutOfRange)
648}
649
650fn write_opt_u8(w: &mut Writer<'_>, v: Option<u8>) -> Result<()> {
651    match v {
652        Some(v) => w.unsigned(u64::from(v), 1),
653        None => w.absent(),
654    }
655}
656
657fn opt_server_id<'a>(r: &mut Reader<'a>) -> Result<Option<ServerId<'a>>> {
658    Ok(r.opt_octet_string()?.map(ServerId::new))
659}
660
661fn write_opt_server_id(w: &mut Writer<'_>, id: Option<ServerId<'_>>) -> Result<()> {
662    w.opt_octet_string(id.map(|id| id.as_bytes()))
663}
664
665impl<'a> Body<'a> {
666    /// The body's tag.
667    pub const fn tag(&self) -> u32 {
668        match self {
669            Self::OpenRequest(_) => tag::OPEN_REQUEST,
670            Self::OpenResponse(_) => tag::OPEN_RESPONSE,
671            Self::CloseRequest(_) => tag::CLOSE_REQUEST,
672            Self::CloseResponse(_) => tag::CLOSE_RESPONSE,
673            Self::GetListRequest(_) => tag::GET_LIST_REQUEST,
674            Self::GetListResponse(_) => tag::GET_LIST_RESPONSE,
675            Self::Attention(_) => tag::ATTENTION_RESPONSE,
676            Self::GetProcParameterRequest(_) => tag::GET_PROC_PARAMETER_REQUEST,
677            Self::GetProcParameterResponse(_) => tag::GET_PROC_PARAMETER_RESPONSE,
678            Self::SetProcParameterRequest(_) => tag::SET_PROC_PARAMETER_REQUEST,
679            Self::GetProfilePackRequest(_) => tag::GET_PROFILE_PACK_REQUEST,
680            Self::GetProfileListRequest(_) => tag::GET_PROFILE_LIST_REQUEST,
681            Self::GetProfileListResponse(_) => tag::GET_PROFILE_LIST_RESPONSE,
682            Self::GetProfilePackResponse(_) => tag::GET_PROFILE_PACK_RESPONSE,
683            Self::Other { tag, .. } => *tag,
684        }
685    }
686
687    #[allow(clippy::too_many_lines)] // One arm per body tag: a table, not logic.
688    fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<Self> {
689        r.list(2)?;
690        let tag = u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
691        let ctx = Ctx::new(options);
692        Ok(match tag {
693            tag::OPEN_REQUEST => {
694                r.list(7)?;
695                Self::OpenRequest(OpenRequest {
696                    codepage: r.opt_octet_string()?,
697                    client_id: r.octet_string()?,
698                    req_file_id: r.octet_string()?,
699                    server_id: opt_server_id(r)?,
700                    username: r.opt_octet_string()?,
701                    password: r.opt_octet_string()?,
702                    sml_version: read_u8(r)?,
703                })
704            }
705            tag::OPEN_RESPONSE => {
706                r.list(6)?;
707                Self::OpenResponse(OpenResponse {
708                    codepage: r.opt_octet_string()?,
709                    client_id: r.opt_octet_string()?,
710                    req_file_id: r.octet_string()?,
711                    server_id: ServerId::new(r.octet_string()?),
712                    ref_time: Time::read_opt(r, options)?,
713                    sml_version: read_u8(r)?,
714                })
715            }
716            tag::CLOSE_REQUEST => {
717                r.list(1)?;
718                Self::CloseRequest(CloseRequest { global_signature: r.opt_octet_string()? })
719            }
720            tag::CLOSE_RESPONSE => {
721                r.list(1)?;
722                Self::CloseResponse(CloseResponse { global_signature: r.opt_octet_string()? })
723            }
724            tag::GET_LIST_REQUEST => {
725                r.list(5)?;
726                Self::GetListRequest(GetListRequest {
727                    client_id: r.octet_string()?,
728                    server_id: opt_server_id(r)?,
729                    username: r.opt_octet_string()?,
730                    password: r.opt_octet_string()?,
731                    list_name: r.opt_octet_string()?,
732                })
733            }
734            tag::GET_LIST_RESPONSE => {
735                r.list(7)?;
736                let client_id = r.opt_octet_string()?;
737                let server_id = ServerId::new(r.octet_string()?);
738                let list_name = r.opt_octet_string()?;
739                let act_sensor_time = Time::read_opt(r, options)?;
740                let dzg = options.dzg_power && server_id.manufacturer() == Some("DZG");
741                let entries = Seq::read(r, Ctx { dzg, ..Ctx::new(options) })?;
742                Self::GetListResponse(GetListResponse {
743                    client_id,
744                    server_id,
745                    list_name,
746                    act_sensor_time,
747                    entries,
748                    list_signature: r.opt_octet_string()?,
749                    act_gateway_time: Time::read_opt(r, options)?,
750                })
751            }
752            tag::ATTENTION_RESPONSE => {
753                r.list(4)?;
754                let server_id = ServerId::new(r.octet_string()?);
755                let number = r.octet_string()?;
756                let message = r.opt_octet_string()?;
757                let details = if r.absent() {
758                    None
759                } else {
760                    let from = r.position();
761                    r.skip()?;
762                    Some(r.slice(from, r.position())?)
763                };
764                Self::Attention(Attention { server_id, number, message, details })
765            }
766            tag::GET_PROC_PARAMETER_REQUEST => {
767                r.list(5)?;
768                Self::GetProcParameterRequest(GetProcParameterRequest {
769                    server_id: opt_server_id(r)?,
770                    username: r.opt_octet_string()?,
771                    password: r.opt_octet_string()?,
772                    tree_path: Seq::read(r, ctx)?,
773                    attribute: r.opt_octet_string()?,
774                })
775            }
776            tag::GET_PROC_PARAMETER_RESPONSE => {
777                r.list(3)?;
778                Self::GetProcParameterResponse(GetProcParameterResponse {
779                    server_id: ServerId::new(r.octet_string()?),
780                    tree_path: Seq::read(r, ctx)?,
781                    tree: Tree::read(r, ctx)?,
782                })
783            }
784            tag::SET_PROC_PARAMETER_REQUEST => {
785                r.list(5)?;
786                Self::SetProcParameterRequest(SetProcParameterRequest {
787                    server_id: opt_server_id(r)?,
788                    username: r.opt_octet_string()?,
789                    password: r.opt_octet_string()?,
790                    tree_path: Seq::read(r, ctx)?,
791                    tree: Tree::read(r, ctx)?,
792                })
793            }
794            tag::GET_PROFILE_PACK_REQUEST => Self::GetProfilePackRequest(GetProfileRequest::read(r, ctx)?),
795            tag::GET_PROFILE_LIST_REQUEST => Self::GetProfileListRequest(GetProfileRequest::read(r, ctx)?),
796            tag::GET_PROFILE_LIST_RESPONSE => {
797                r.list(9)?;
798                Self::GetProfileListResponse(GetProfileListResponse {
799                    server_id: ServerId::new(r.octet_string()?),
800                    act_time: Time::read(r, options)?,
801                    reg_period: u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?,
802                    tree_path: Seq::read(r, ctx)?,
803                    val_time: Time::read(r, options)?,
804                    status: r.unsigned()?,
805                    entries: Seq::read(r, ctx)?,
806                    rawdata: r.opt_octet_string()?,
807                    period_signature: r.opt_octet_string()?,
808                })
809            }
810            tag::GET_PROFILE_PACK_RESPONSE => {
811                Self::GetProfilePackResponse(GetProfilePackResponse::read(r, ctx)?)
812            }
813            other => {
814                let from = r.position();
815                r.skip()?;
816                Self::Other { tag: other, raw: r.slice(from, r.position())? }
817            }
818        })
819    }
820
821    /// Write the body (`List(2) { tag, body }`).
822    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
823        w.list(2)?;
824        w.unsigned(u64::from(self.tag()), 4)?;
825        match *self {
826            Self::OpenRequest(o) => {
827                w.list(7)?;
828                w.opt_octet_string(o.codepage)?;
829                w.octet_string(o.client_id)?;
830                w.octet_string(o.req_file_id)?;
831                write_opt_server_id(w, o.server_id)?;
832                w.opt_octet_string(o.username)?;
833                w.opt_octet_string(o.password)?;
834                write_opt_u8(w, o.sml_version)
835            }
836            Self::OpenResponse(o) => {
837                w.list(6)?;
838                w.opt_octet_string(o.codepage)?;
839                w.opt_octet_string(o.client_id)?;
840                w.octet_string(o.req_file_id)?;
841                w.octet_string(o.server_id.as_bytes())?;
842                Time::write_opt(o.ref_time, w)?;
843                write_opt_u8(w, o.sml_version)
844            }
845            Self::CloseRequest(CloseRequest { global_signature })
846            | Self::CloseResponse(CloseResponse { global_signature }) => {
847                w.list(1)?;
848                w.opt_octet_string(global_signature)
849            }
850            Self::GetListRequest(g) => {
851                w.list(5)?;
852                w.octet_string(g.client_id)?;
853                write_opt_server_id(w, g.server_id)?;
854                w.opt_octet_string(g.username)?;
855                w.opt_octet_string(g.password)?;
856                w.opt_octet_string(g.list_name)
857            }
858            Self::GetListResponse(g) => {
859                w.list(7)?;
860                w.opt_octet_string(g.client_id)?;
861                w.octet_string(g.server_id.as_bytes())?;
862                w.opt_octet_string(g.list_name)?;
863                Time::write_opt(g.act_sensor_time, w)?;
864                g.entries.write(w)?;
865                w.opt_octet_string(g.list_signature)?;
866                Time::write_opt(g.act_gateway_time, w)
867            }
868            Self::Attention(a) => {
869                w.list(4)?;
870                w.octet_string(a.server_id.as_bytes())?;
871                w.octet_string(a.number)?;
872                w.opt_octet_string(a.message)?;
873                match a.details {
874                    Some(raw) => w.raw(one_element(raw)?),
875                    None => w.absent(),
876                }
877            }
878            Self::GetProcParameterRequest(g) => {
879                w.list(5)?;
880                write_opt_server_id(w, g.server_id)?;
881                w.opt_octet_string(g.username)?;
882                w.opt_octet_string(g.password)?;
883                g.tree_path.write(w)?;
884                w.opt_octet_string(g.attribute)
885            }
886            Self::GetProcParameterResponse(g) => {
887                w.list(3)?;
888                w.octet_string(g.server_id.as_bytes())?;
889                g.tree_path.write(w)?;
890                g.tree.write(w)
891            }
892            Self::SetProcParameterRequest(s) => {
893                w.list(5)?;
894                write_opt_server_id(w, s.server_id)?;
895                w.opt_octet_string(s.username)?;
896                w.opt_octet_string(s.password)?;
897                s.tree_path.write(w)?;
898                s.tree.write(w)
899            }
900            Self::GetProfilePackRequest(g) | Self::GetProfileListRequest(g) => g.write(w),
901            Self::GetProfileListResponse(g) => {
902                w.list(9)?;
903                w.octet_string(g.server_id.as_bytes())?;
904                g.act_time.write(w)?;
905                w.unsigned(u64::from(g.reg_period), 4)?;
906                g.tree_path.write(w)?;
907                g.val_time.write(w)?;
908                w.unsigned(g.status, 8)?;
909                g.entries.write(w)?;
910                w.opt_octet_string(g.rawdata)?;
911                w.opt_octet_string(g.period_signature)
912            }
913            Self::GetProfilePackResponse(g) => g.write(w),
914            Self::Other { raw, .. } => w.raw(one_element(raw)?),
915        }
916    }
917}
918
919impl<'a> GetProfileRequest<'a> {
920    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
921        r.list(9)?;
922        Ok(Self {
923            server_id: opt_server_id(r)?,
924            username: r.opt_octet_string()?,
925            password: r.opt_octet_string()?,
926            with_rawdata: if r.absent() { None } else { Some(r.boolean()?) },
927            begin_time: Time::read_opt(r, ctx.options)?,
928            end_time: Time::read_opt(r, ctx.options)?,
929            tree_path: Seq::read(r, ctx)?,
930            objects: Seq::read_opt(r, ctx)?,
931            details: Tree::read_opt(r, ctx)?,
932        })
933    }
934
935    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
936        w.list(9)?;
937        write_opt_server_id(w, self.server_id)?;
938        w.opt_octet_string(self.username)?;
939        w.opt_octet_string(self.password)?;
940        match self.with_rawdata {
941            Some(b) => w.boolean(b)?,
942            None => w.absent()?,
943        }
944        Time::write_opt(self.begin_time, w)?;
945        Time::write_opt(self.end_time, w)?;
946        self.tree_path.write(w)?;
947        Seq::write_opt(self.objects, w)?;
948        Tree::write_opt(self.details.as_ref(), w)
949    }
950}
951
952/// `raw`, if it is exactly one encoded SML element: raw bytes written into a message must
953/// not change its structure.
954fn one_element(raw: &[u8]) -> Result<&[u8]> {
955    let mut r = Reader::new(raw);
956    r.skip()?;
957    if r.is_empty() { Ok(raw) } else { Err(Error::InvalidLength) }
958}
959
960/// The messages of one SML file (one transport payload).
961///
962/// Stops after the first error: past a malformed message there is no reliable way to
963/// find the next one. [`Messages::offset`] says where it was.
964#[derive(Clone, Debug)] // `Reader`'s Debug shows no bytes.
965pub struct Messages<'a> {
966    r: Reader<'a>,
967    options: ParseOptions,
968    done: bool,
969    last: usize,
970}
971
972impl<'a> Messages<'a> {
973    /// Messages in `payload`, parsed with `options`.
974    pub const fn new(payload: &'a [u8], options: ParseOptions) -> Self {
975        Self { r: Reader::new(payload), options, done: false, last: 0 }
976    }
977
978    /// The byte offset in the payload where the message returned last starts: after an
979    /// error, where the failing message starts.
980    pub const fn offset(&self) -> usize {
981        self.last
982    }
983}
984
985impl<'a> Iterator for Messages<'a> {
986    type Item = Result<Message<'a>>;
987
988    fn next(&mut self) -> Option<Self::Item> {
989        if self.done || self.r.is_empty() {
990            return None;
991        }
992        self.last = self.r.position();
993        let item = Message::read(&mut self.r, self.options);
994        self.done = item.is_err();
995        Some(item)
996    }
997}
998
999/// The readings of one SML file in one call: every message is parsed (any error is
1000/// returned) and the first `GetListResponse` comes back.
1001pub fn readout_with(payload: &[u8], options: ParseOptions) -> Result<GetListResponse<'_>> {
1002    let mut list = None;
1003    for message in Messages::new(payload, options) {
1004        if let (None, Body::GetListResponse(l)) = (list, message?.body) {
1005            list = Some(l);
1006        }
1007    }
1008    list.ok_or(Error::NoReadings)
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013    extern crate std;
1014    use super::*;
1015    use std::format;
1016
1017    // 001-real-meter-readiness/SR-006
1018    #[test]
1019    fn debug_never_prints_a_password() {
1020        let open = OpenRequest {
1021            codepage: None,
1022            client_id: b"client",
1023            req_file_id: b"1",
1024            server_id: None,
1025            username: Some(b"user"),
1026            password: Some(b"secret"),
1027            sml_version: None,
1028        };
1029        let shown = format!("{open:?} {:?}", Body::OpenRequest(open));
1030        assert!(!shown.contains("secret") && !shown.contains("115, 101, 99"), "{shown}");
1031        assert!(shown.contains("<redacted>"));
1032        let get = GetListRequest {
1033            client_id: b"c",
1034            server_id: None,
1035            username: None,
1036            password: Some(b"pw"),
1037            list_name: None,
1038        };
1039        let shown = format!("{get:?}");
1040        assert!(!shown.contains("112, 119") && shown.contains("<redacted>"), "{shown}");
1041        let none = GetListRequest { password: None, ..get };
1042        assert!(format!("{none:?}").contains("password: None"));
1043    }
1044
1045    // 002-complete-protocol/SR-003: every request kind that carries a password redacts it,
1046    // printed directly, inside a Body and inside a Message.
1047    #[test]
1048    fn redact_every_credential_carrying_request() {
1049        let pw: &[u8] = b"hunter2";
1050        let path = NameList::from_slice(&[b"p"]);
1051        let tree = Tree { name: b"n", value: None, children: None };
1052        let profile = GetProfileRequest {
1053            server_id: None,
1054            username: Some(b"u"),
1055            password: Some(pw),
1056            with_rawdata: None,
1057            begin_time: None,
1058            end_time: None,
1059            tree_path: path,
1060            objects: None,
1061            details: None,
1062        };
1063        let bodies = [
1064            Body::OpenRequest(OpenRequest {
1065                codepage: None,
1066                client_id: b"c",
1067                req_file_id: b"f",
1068                server_id: None,
1069                username: Some(b"u"),
1070                password: Some(pw),
1071                sml_version: None,
1072            }),
1073            Body::GetListRequest(GetListRequest {
1074                client_id: b"c",
1075                server_id: None,
1076                username: None,
1077                password: Some(pw),
1078                list_name: None,
1079            }),
1080            Body::GetProcParameterRequest(GetProcParameterRequest {
1081                server_id: None,
1082                username: None,
1083                password: Some(pw),
1084                tree_path: path,
1085                attribute: None,
1086            }),
1087            Body::SetProcParameterRequest(SetProcParameterRequest {
1088                server_id: None,
1089                username: None,
1090                password: Some(pw),
1091                tree_path: path,
1092                tree,
1093            }),
1094            Body::GetProfilePackRequest(profile),
1095            Body::GetProfileListRequest(profile),
1096        ];
1097        for body in bodies {
1098            let message = Message { transaction_id: b"t", group_no: 0, abort_on_error: 0, body };
1099            let shown = format!("{body:?} {message:?} {message:#?}");
1100            assert!(!shown.contains("hunter2") && !shown.contains("104, 117, 110"), "{shown}");
1101            assert!(shown.contains("<redacted>"), "{shown}");
1102            // Written and decoded again, the password is still redacted.
1103            let mut buf = [0u8; 256];
1104            let mut w = Writer::new(&mut buf);
1105            message.write(&mut w).unwrap();
1106            let n = w.position();
1107            let again = Message::read(&mut Reader::new(&buf[..n]), ParseOptions::default()).unwrap();
1108            assert_eq!(again, message);
1109            assert!(!format!("{again:?}").contains("104, 117, 110"));
1110        }
1111    }
1112
1113    // 001-real-meter-readiness/SR-006: no Debug output of a parser shows payload bytes.
1114    #[test]
1115    fn debug_of_parsers_never_prints_payload_bytes() {
1116        let payload = b"\x76secret-password";
1117        let shown = format!(
1118            "{:?} {:?} {:?}",
1119            Messages::new(payload, ParseOptions::default()),
1120            Reader::new(payload),
1121            crate::Decoder::new([0u8; 8])
1122        );
1123        assert!(!shown.contains("115, 101, 99") && !shown.contains("secret"), "{shown}");
1124    }
1125
1126    #[test]
1127    fn raw_parts_must_be_one_element_or_nothing_is_written() {
1128        let mut buf = [0u8; 64];
1129        for raw in [&[][..], &[0x01, 0x01], &[0x72, 0x01]] {
1130            let m = Message {
1131                transaction_id: b"t",
1132                group_no: 0,
1133                abort_on_error: 0,
1134                body: Body::Other { tag: 0x500, raw },
1135            };
1136            assert!(m.write(&mut Writer::new(&mut buf)).is_err(), "{raw:02x?}");
1137            let a =
1138                Attention { server_id: ServerId::new(b"s"), number: b"n", message: None, details: Some(raw) };
1139            let m = Message { body: Body::Attention(a), ..m };
1140            assert!(m.write(&mut Writer::new(&mut buf)).is_err(), "{raw:02x?}");
1141        }
1142    }
1143
1144    #[test]
1145    fn lists_compare_by_what_they_yield() {
1146        let dzg_meter: &[u8] = &[0x0a, 0x01, b'D', b'Z', b'G', 0, 2, 0x82, 0x22, 0x5e];
1147        let entries = [ListEntry::number(Obis::POWER, Unit::W, -2, -29_912)];
1148        let body = Body::GetListResponse(GetListResponse {
1149            client_id: None,
1150            server_id: ServerId::new(dzg_meter),
1151            list_name: None,
1152            act_sensor_time: None,
1153            entries: ListEntries::from_slice(&entries),
1154            list_signature: None,
1155            act_gateway_time: None,
1156        });
1157        let mut buf = [0u8; 128];
1158        let mut w = Writer::new(&mut buf);
1159        Message { transaction_id: b"t", group_no: 0, abort_on_error: 0, body }.write(&mut w).unwrap();
1160        let n = w.position();
1161        let plain = readout_with(&buf[..n], ParseOptions::default()).unwrap();
1162        let fixed = readout_with(&buf[..n], ParseOptions::default().with_dzg_power(true)).unwrap();
1163        let off =
1164            readout_with(&buf[..n], ParseOptions { crc: CrcCheck::Off, ..ParseOptions::default() }).unwrap();
1165        // Built and decoded lists are equal; the CRC mode does not matter, the DZG rule does.
1166        assert_eq!(plain.entries, ListEntries::from_slice(&entries));
1167        assert_eq!(plain.entries, off.entries);
1168        assert_ne!(plain.entries, fixed.entries);
1169        assert_eq!(format!("{:?}", plain.entries), "Seq { len: 1, .. }");
1170    }
1171
1172    #[test]
1173    fn dzg_correction_only_touches_short_negatives() {
1174        assert_eq!(dzg_unsigned(SmlValue::Int(0), 2), SmlValue::Int(0));
1175        assert_eq!(dzg_unsigned(SmlValue::Int(-29_912), 2), SmlValue::Uint(35_624));
1176        assert_eq!(dzg_unsigned(SmlValue::Int(-1), 1), SmlValue::Uint(255));
1177        assert_eq!(dzg_unsigned(SmlValue::Int(-1), 3), SmlValue::Uint(0xFF_FFFF));
1178        assert_eq!(dzg_unsigned(SmlValue::Int(-60_525), 4), SmlValue::Int(-60_525));
1179        assert_eq!(dzg_unsigned(SmlValue::Int(5), 2), SmlValue::Int(5));
1180        assert_eq!(dzg_unsigned(SmlValue::Uint(5), 2), SmlValue::Uint(5));
1181    }
1182}