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 numeric entry: `value × 10^scaler` in `unit`, no status, time or signature.
477    pub const fn number(obis: Obis, unit: Unit, scaler: i8, value: i64) -> Self {
478        Self {
479            obis,
480            status: None,
481            val_time: None,
482            unit: Some(unit),
483            scaler: Some(scaler),
484            value: SmlValue::Int(value),
485            value_signature: None,
486        }
487    }
488
489    /// A byte-string entry (identifiers, text).
490    pub const fn bytes(obis: Obis, value: &'a [u8]) -> Self {
491        Self {
492            obis,
493            status: None,
494            val_time: None,
495            unit: None,
496            scaler: None,
497            value: SmlValue::Bytes(value),
498            value_signature: None,
499        }
500    }
501}
502
503impl<'a> Element<'a> for ListEntry<'a> {
504    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
505        let (options, dzg) = (ctx.options, ctx.dzg);
506        r.list(7)?;
507        let obis = Obis::from_bytes(r.octet_string()?)?;
508        let status = r.opt_unsigned()?;
509        let val_time = Time::read_opt(r, options)?;
510        let unit = r
511            .opt_unsigned()?
512            .map(|u| u8::try_from(u).map(Unit))
513            .transpose()
514            .map_err(|_| Error::ValueOutOfRange)?;
515        let scaler = r.opt_integer()?.map(i8::try_from).transpose().map_err(|_| Error::ValueOutOfRange)?;
516        let (mut value, width) = SmlValue::read(r, options)?;
517        if dzg && obis.is_active_power() {
518            value = dzg_unsigned(value, width);
519        }
520        let value_signature = r.opt_octet_string()?;
521        Ok(Self { obis, status, val_time, unit, scaler, value, value_signature })
522    }
523
524    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
525        ListEntry::write(self, w)
526    }
527}
528
529impl ListEntry<'_> {
530    /// Write the entry: status and value in the smallest width that holds them.
531    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
532        w.list(7)?;
533        w.octet_string(&self.obis.0)?;
534        match self.status {
535            Some(s) => w.unsigned_min(s)?,
536            None => w.absent()?,
537        }
538        Time::write_opt(self.val_time, w)?;
539        match self.unit {
540            Some(u) => w.unsigned(u64::from(u.0), 1)?,
541            None => w.absent()?,
542        }
543        match self.scaler {
544            Some(s) => w.integer(i64::from(s), 1)?,
545            None => w.absent()?,
546        }
547        self.value.write(w)?;
548        w.opt_octet_string(self.value_signature)
549    }
550
551    /// The value as an exact [`Quantity`], when it is numeric.
552    pub fn quantity(&self) -> Option<Quantity> {
553        let mantissa = match self.value {
554            SmlValue::Int(v) => i128::from(v),
555            SmlValue::Uint(v) => i128::from(v),
556            SmlValue::Bool(_) | SmlValue::Bytes(_) | SmlValue::Time(_) => return None,
557        };
558        Some(Quantity { mantissa, exponent: self.scaler.unwrap_or(0), unit: self.unit })
559    }
560}
561
562/// The DZG DVS74 correction: a negative `Integer` of 1–3 bytes is the unsigned number of
563/// the same bytes.
564fn dzg_unsigned(value: SmlValue<'_>, width: usize) -> SmlValue<'_> {
565    match value {
566        SmlValue::Int(v) if v < 0 && (1..=3).contains(&width) => {
567            let bits = u64::from_be_bytes(v.to_be_bytes());
568            SmlValue::Uint(bits & ((1u64 << (8 * width)) - 1))
569        }
570        other => other,
571    }
572}
573
574impl<'a> Message<'a> {
575    /// Parse one message at the reader's position and check its CRC.
576    pub fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<Self> {
577        let start = r.position();
578        r.list(6)?;
579        let transaction_id = r.octet_string()?;
580        let group_no = u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
581        let abort_on_error = u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
582        let body = Body::read(r, options)?;
583        let crc_end = r.position();
584        // An Unsigned16 may drop its leading zero byte (ISKRA MT691 does), never add one.
585        if r.clone().read_tl().is_ok_and(|tl| tl.kind == Kind::Unsigned && tl.len > 2) {
586            return Err(Error::InvalidLength);
587        }
588        let found = u16::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
589        let covered = r.slice(start, crc_end)?;
590        let computed = x25(covered);
591        let accepted = match options.crc {
592            CrcCheck::Lenient => options.crc.accepts(computed, kermit(covered), found),
593            check => check.accepts(computed, 0, found),
594        };
595        if !accepted {
596            return Err(Error::MessageCrc { computed, found });
597        }
598        r.end_of_message()?;
599        Ok(Self { transaction_id, group_no, abort_on_error, body })
600    }
601
602    /// Write the message with its CRC (CRC-16/X-25, low byte first) and end-of-message
603    /// byte.
604    ///
605    /// Reading the result yields an equal message. The bytes may differ from the ones a
606    /// message was decoded from, because integer widths are not kept. An empty optional
607    /// octet string (`Some(&[])`) is written as `01`, which SML reads as absent: the two
608    /// cannot be told apart on the wire.
609    ///
610    /// Raw parts (`Attention::details`, `Body::Other`) must each be exactly one encoded
611    /// element, or the result is [`Error::InvalidLength`] and nothing is written that
612    /// would carry a valid CRC over a broken structure.
613    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
614        let start = w.position();
615        w.list(6)?;
616        w.octet_string(self.transaction_id)?;
617        w.unsigned(u64::from(self.group_no), 1)?;
618        w.unsigned(u64::from(self.abort_on_error), 1)?;
619        self.body.write(w)?;
620        let crc = x25(w.written().get(start..).unwrap_or(&[]));
621        w.unsigned(u64::from(crc.swap_bytes()), 2)?;
622        w.end_of_message()
623    }
624}
625
626fn read_u8(r: &mut Reader<'_>) -> Result<Option<u8>> {
627    r.opt_unsigned()?.map(u8::try_from).transpose().map_err(|_| Error::ValueOutOfRange)
628}
629
630fn write_opt_u8(w: &mut Writer<'_>, v: Option<u8>) -> Result<()> {
631    match v {
632        Some(v) => w.unsigned(u64::from(v), 1),
633        None => w.absent(),
634    }
635}
636
637fn opt_server_id<'a>(r: &mut Reader<'a>) -> Result<Option<ServerId<'a>>> {
638    Ok(r.opt_octet_string()?.map(ServerId::new))
639}
640
641fn write_opt_server_id(w: &mut Writer<'_>, id: Option<ServerId<'_>>) -> Result<()> {
642    w.opt_octet_string(id.map(|id| id.as_bytes()))
643}
644
645impl<'a> Body<'a> {
646    /// The body's tag.
647    pub const fn tag(&self) -> u32 {
648        match self {
649            Self::OpenRequest(_) => tag::OPEN_REQUEST,
650            Self::OpenResponse(_) => tag::OPEN_RESPONSE,
651            Self::CloseRequest(_) => tag::CLOSE_REQUEST,
652            Self::CloseResponse(_) => tag::CLOSE_RESPONSE,
653            Self::GetListRequest(_) => tag::GET_LIST_REQUEST,
654            Self::GetListResponse(_) => tag::GET_LIST_RESPONSE,
655            Self::Attention(_) => tag::ATTENTION_RESPONSE,
656            Self::GetProcParameterRequest(_) => tag::GET_PROC_PARAMETER_REQUEST,
657            Self::GetProcParameterResponse(_) => tag::GET_PROC_PARAMETER_RESPONSE,
658            Self::SetProcParameterRequest(_) => tag::SET_PROC_PARAMETER_REQUEST,
659            Self::GetProfilePackRequest(_) => tag::GET_PROFILE_PACK_REQUEST,
660            Self::GetProfileListRequest(_) => tag::GET_PROFILE_LIST_REQUEST,
661            Self::GetProfileListResponse(_) => tag::GET_PROFILE_LIST_RESPONSE,
662            Self::GetProfilePackResponse(_) => tag::GET_PROFILE_PACK_RESPONSE,
663            Self::Other { tag, .. } => *tag,
664        }
665    }
666
667    #[allow(clippy::too_many_lines)] // One arm per body tag: a table, not logic.
668    fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<Self> {
669        r.list(2)?;
670        let tag = u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
671        let ctx = Ctx::new(options);
672        Ok(match tag {
673            tag::OPEN_REQUEST => {
674                r.list(7)?;
675                Self::OpenRequest(OpenRequest {
676                    codepage: r.opt_octet_string()?,
677                    client_id: r.octet_string()?,
678                    req_file_id: r.octet_string()?,
679                    server_id: opt_server_id(r)?,
680                    username: r.opt_octet_string()?,
681                    password: r.opt_octet_string()?,
682                    sml_version: read_u8(r)?,
683                })
684            }
685            tag::OPEN_RESPONSE => {
686                r.list(6)?;
687                Self::OpenResponse(OpenResponse {
688                    codepage: r.opt_octet_string()?,
689                    client_id: r.opt_octet_string()?,
690                    req_file_id: r.octet_string()?,
691                    server_id: ServerId::new(r.octet_string()?),
692                    ref_time: Time::read_opt(r, options)?,
693                    sml_version: read_u8(r)?,
694                })
695            }
696            tag::CLOSE_REQUEST => {
697                r.list(1)?;
698                Self::CloseRequest(CloseRequest { global_signature: r.opt_octet_string()? })
699            }
700            tag::CLOSE_RESPONSE => {
701                r.list(1)?;
702                Self::CloseResponse(CloseResponse { global_signature: r.opt_octet_string()? })
703            }
704            tag::GET_LIST_REQUEST => {
705                r.list(5)?;
706                Self::GetListRequest(GetListRequest {
707                    client_id: r.octet_string()?,
708                    server_id: opt_server_id(r)?,
709                    username: r.opt_octet_string()?,
710                    password: r.opt_octet_string()?,
711                    list_name: r.opt_octet_string()?,
712                })
713            }
714            tag::GET_LIST_RESPONSE => {
715                r.list(7)?;
716                let client_id = r.opt_octet_string()?;
717                let server_id = ServerId::new(r.octet_string()?);
718                let list_name = r.opt_octet_string()?;
719                let act_sensor_time = Time::read_opt(r, options)?;
720                let dzg = options.dzg_power && server_id.manufacturer() == Some("DZG");
721                let entries = Seq::read(r, Ctx { dzg, ..Ctx::new(options) })?;
722                Self::GetListResponse(GetListResponse {
723                    client_id,
724                    server_id,
725                    list_name,
726                    act_sensor_time,
727                    entries,
728                    list_signature: r.opt_octet_string()?,
729                    act_gateway_time: Time::read_opt(r, options)?,
730                })
731            }
732            tag::ATTENTION_RESPONSE => {
733                r.list(4)?;
734                let server_id = ServerId::new(r.octet_string()?);
735                let number = r.octet_string()?;
736                let message = r.opt_octet_string()?;
737                let details = if r.absent() {
738                    None
739                } else {
740                    let from = r.position();
741                    r.skip()?;
742                    Some(r.slice(from, r.position())?)
743                };
744                Self::Attention(Attention { server_id, number, message, details })
745            }
746            tag::GET_PROC_PARAMETER_REQUEST => {
747                r.list(5)?;
748                Self::GetProcParameterRequest(GetProcParameterRequest {
749                    server_id: opt_server_id(r)?,
750                    username: r.opt_octet_string()?,
751                    password: r.opt_octet_string()?,
752                    tree_path: Seq::read(r, ctx)?,
753                    attribute: r.opt_octet_string()?,
754                })
755            }
756            tag::GET_PROC_PARAMETER_RESPONSE => {
757                r.list(3)?;
758                Self::GetProcParameterResponse(GetProcParameterResponse {
759                    server_id: ServerId::new(r.octet_string()?),
760                    tree_path: Seq::read(r, ctx)?,
761                    tree: Tree::read(r, ctx)?,
762                })
763            }
764            tag::SET_PROC_PARAMETER_REQUEST => {
765                r.list(5)?;
766                Self::SetProcParameterRequest(SetProcParameterRequest {
767                    server_id: opt_server_id(r)?,
768                    username: r.opt_octet_string()?,
769                    password: r.opt_octet_string()?,
770                    tree_path: Seq::read(r, ctx)?,
771                    tree: Tree::read(r, ctx)?,
772                })
773            }
774            tag::GET_PROFILE_PACK_REQUEST => Self::GetProfilePackRequest(GetProfileRequest::read(r, ctx)?),
775            tag::GET_PROFILE_LIST_REQUEST => Self::GetProfileListRequest(GetProfileRequest::read(r, ctx)?),
776            tag::GET_PROFILE_LIST_RESPONSE => {
777                r.list(9)?;
778                Self::GetProfileListResponse(GetProfileListResponse {
779                    server_id: ServerId::new(r.octet_string()?),
780                    act_time: Time::read(r, options)?,
781                    reg_period: u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?,
782                    tree_path: Seq::read(r, ctx)?,
783                    val_time: Time::read(r, options)?,
784                    status: r.unsigned()?,
785                    entries: Seq::read(r, ctx)?,
786                    rawdata: r.opt_octet_string()?,
787                    period_signature: r.opt_octet_string()?,
788                })
789            }
790            tag::GET_PROFILE_PACK_RESPONSE => {
791                Self::GetProfilePackResponse(GetProfilePackResponse::read(r, ctx)?)
792            }
793            other => {
794                let from = r.position();
795                r.skip()?;
796                Self::Other { tag: other, raw: r.slice(from, r.position())? }
797            }
798        })
799    }
800
801    /// Write the body (`List(2) { tag, body }`).
802    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
803        w.list(2)?;
804        w.unsigned(u64::from(self.tag()), 4)?;
805        match *self {
806            Self::OpenRequest(o) => {
807                w.list(7)?;
808                w.opt_octet_string(o.codepage)?;
809                w.octet_string(o.client_id)?;
810                w.octet_string(o.req_file_id)?;
811                write_opt_server_id(w, o.server_id)?;
812                w.opt_octet_string(o.username)?;
813                w.opt_octet_string(o.password)?;
814                write_opt_u8(w, o.sml_version)
815            }
816            Self::OpenResponse(o) => {
817                w.list(6)?;
818                w.opt_octet_string(o.codepage)?;
819                w.opt_octet_string(o.client_id)?;
820                w.octet_string(o.req_file_id)?;
821                w.octet_string(o.server_id.as_bytes())?;
822                Time::write_opt(o.ref_time, w)?;
823                write_opt_u8(w, o.sml_version)
824            }
825            Self::CloseRequest(CloseRequest { global_signature })
826            | Self::CloseResponse(CloseResponse { global_signature }) => {
827                w.list(1)?;
828                w.opt_octet_string(global_signature)
829            }
830            Self::GetListRequest(g) => {
831                w.list(5)?;
832                w.octet_string(g.client_id)?;
833                write_opt_server_id(w, g.server_id)?;
834                w.opt_octet_string(g.username)?;
835                w.opt_octet_string(g.password)?;
836                w.opt_octet_string(g.list_name)
837            }
838            Self::GetListResponse(g) => {
839                w.list(7)?;
840                w.opt_octet_string(g.client_id)?;
841                w.octet_string(g.server_id.as_bytes())?;
842                w.opt_octet_string(g.list_name)?;
843                Time::write_opt(g.act_sensor_time, w)?;
844                g.entries.write(w)?;
845                w.opt_octet_string(g.list_signature)?;
846                Time::write_opt(g.act_gateway_time, w)
847            }
848            Self::Attention(a) => {
849                w.list(4)?;
850                w.octet_string(a.server_id.as_bytes())?;
851                w.octet_string(a.number)?;
852                w.opt_octet_string(a.message)?;
853                match a.details {
854                    Some(raw) => w.raw(one_element(raw)?),
855                    None => w.absent(),
856                }
857            }
858            Self::GetProcParameterRequest(g) => {
859                w.list(5)?;
860                write_opt_server_id(w, g.server_id)?;
861                w.opt_octet_string(g.username)?;
862                w.opt_octet_string(g.password)?;
863                g.tree_path.write(w)?;
864                w.opt_octet_string(g.attribute)
865            }
866            Self::GetProcParameterResponse(g) => {
867                w.list(3)?;
868                w.octet_string(g.server_id.as_bytes())?;
869                g.tree_path.write(w)?;
870                g.tree.write(w)
871            }
872            Self::SetProcParameterRequest(s) => {
873                w.list(5)?;
874                write_opt_server_id(w, s.server_id)?;
875                w.opt_octet_string(s.username)?;
876                w.opt_octet_string(s.password)?;
877                s.tree_path.write(w)?;
878                s.tree.write(w)
879            }
880            Self::GetProfilePackRequest(g) | Self::GetProfileListRequest(g) => g.write(w),
881            Self::GetProfileListResponse(g) => {
882                w.list(9)?;
883                w.octet_string(g.server_id.as_bytes())?;
884                g.act_time.write(w)?;
885                w.unsigned(u64::from(g.reg_period), 4)?;
886                g.tree_path.write(w)?;
887                g.val_time.write(w)?;
888                w.unsigned(g.status, 8)?;
889                g.entries.write(w)?;
890                w.opt_octet_string(g.rawdata)?;
891                w.opt_octet_string(g.period_signature)
892            }
893            Self::GetProfilePackResponse(g) => g.write(w),
894            Self::Other { raw, .. } => w.raw(one_element(raw)?),
895        }
896    }
897}
898
899impl<'a> GetProfileRequest<'a> {
900    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
901        r.list(9)?;
902        Ok(Self {
903            server_id: opt_server_id(r)?,
904            username: r.opt_octet_string()?,
905            password: r.opt_octet_string()?,
906            with_rawdata: if r.absent() { None } else { Some(r.boolean()?) },
907            begin_time: Time::read_opt(r, ctx.options)?,
908            end_time: Time::read_opt(r, ctx.options)?,
909            tree_path: Seq::read(r, ctx)?,
910            objects: Seq::read_opt(r, ctx)?,
911            details: Tree::read_opt(r, ctx)?,
912        })
913    }
914
915    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
916        w.list(9)?;
917        write_opt_server_id(w, self.server_id)?;
918        w.opt_octet_string(self.username)?;
919        w.opt_octet_string(self.password)?;
920        match self.with_rawdata {
921            Some(b) => w.boolean(b)?,
922            None => w.absent()?,
923        }
924        Time::write_opt(self.begin_time, w)?;
925        Time::write_opt(self.end_time, w)?;
926        self.tree_path.write(w)?;
927        Seq::write_opt(self.objects, w)?;
928        Tree::write_opt(self.details.as_ref(), w)
929    }
930}
931
932/// `raw`, if it is exactly one encoded SML element: raw bytes written into a message must
933/// not change its structure.
934fn one_element(raw: &[u8]) -> Result<&[u8]> {
935    let mut r = Reader::new(raw);
936    r.skip()?;
937    if r.is_empty() { Ok(raw) } else { Err(Error::InvalidLength) }
938}
939
940/// The messages of one SML file (one transport payload).
941///
942/// Stops after the first error: past a malformed message there is no reliable way to
943/// find the next one. [`Messages::offset`] says where it was.
944#[derive(Clone, Debug)] // `Reader`'s Debug shows no bytes.
945pub struct Messages<'a> {
946    r: Reader<'a>,
947    options: ParseOptions,
948    done: bool,
949    last: usize,
950}
951
952impl<'a> Messages<'a> {
953    /// Messages in `payload`, parsed with `options`.
954    pub const fn new(payload: &'a [u8], options: ParseOptions) -> Self {
955        Self { r: Reader::new(payload), options, done: false, last: 0 }
956    }
957
958    /// The byte offset in the payload where the message returned last starts: after an
959    /// error, where the failing message starts.
960    pub const fn offset(&self) -> usize {
961        self.last
962    }
963}
964
965impl<'a> Iterator for Messages<'a> {
966    type Item = Result<Message<'a>>;
967
968    fn next(&mut self) -> Option<Self::Item> {
969        if self.done || self.r.is_empty() {
970            return None;
971        }
972        self.last = self.r.position();
973        let item = Message::read(&mut self.r, self.options);
974        self.done = item.is_err();
975        Some(item)
976    }
977}
978
979/// The readings of one SML file in one call: every message is parsed (any error is
980/// returned) and the first `GetListResponse` comes back.
981pub fn readout_with(payload: &[u8], options: ParseOptions) -> Result<GetListResponse<'_>> {
982    let mut list = None;
983    for message in Messages::new(payload, options) {
984        if let (None, Body::GetListResponse(l)) = (list, message?.body) {
985            list = Some(l);
986        }
987    }
988    list.ok_or(Error::NoReadings)
989}
990
991#[cfg(test)]
992mod tests {
993    extern crate std;
994    use super::*;
995    use std::format;
996
997    // 001-real-meter-readiness/SR-006
998    #[test]
999    fn debug_never_prints_a_password() {
1000        let open = OpenRequest {
1001            codepage: None,
1002            client_id: b"client",
1003            req_file_id: b"1",
1004            server_id: None,
1005            username: Some(b"user"),
1006            password: Some(b"secret"),
1007            sml_version: None,
1008        };
1009        let shown = format!("{open:?} {:?}", Body::OpenRequest(open));
1010        assert!(!shown.contains("secret") && !shown.contains("115, 101, 99"), "{shown}");
1011        assert!(shown.contains("<redacted>"));
1012        let get = GetListRequest {
1013            client_id: b"c",
1014            server_id: None,
1015            username: None,
1016            password: Some(b"pw"),
1017            list_name: None,
1018        };
1019        let shown = format!("{get:?}");
1020        assert!(!shown.contains("112, 119") && shown.contains("<redacted>"), "{shown}");
1021        let none = GetListRequest { password: None, ..get };
1022        assert!(format!("{none:?}").contains("password: None"));
1023    }
1024
1025    // 002-complete-protocol/SR-003: every request kind that carries a password redacts it,
1026    // printed directly, inside a Body and inside a Message.
1027    #[test]
1028    fn redact_every_credential_carrying_request() {
1029        let pw: &[u8] = b"hunter2";
1030        let path = NameList::from_slice(&[b"p"]);
1031        let tree = Tree { name: b"n", value: None, children: None };
1032        let profile = GetProfileRequest {
1033            server_id: None,
1034            username: Some(b"u"),
1035            password: Some(pw),
1036            with_rawdata: None,
1037            begin_time: None,
1038            end_time: None,
1039            tree_path: path,
1040            objects: None,
1041            details: None,
1042        };
1043        let bodies = [
1044            Body::OpenRequest(OpenRequest {
1045                codepage: None,
1046                client_id: b"c",
1047                req_file_id: b"f",
1048                server_id: None,
1049                username: Some(b"u"),
1050                password: Some(pw),
1051                sml_version: None,
1052            }),
1053            Body::GetListRequest(GetListRequest {
1054                client_id: b"c",
1055                server_id: None,
1056                username: None,
1057                password: Some(pw),
1058                list_name: None,
1059            }),
1060            Body::GetProcParameterRequest(GetProcParameterRequest {
1061                server_id: None,
1062                username: None,
1063                password: Some(pw),
1064                tree_path: path,
1065                attribute: None,
1066            }),
1067            Body::SetProcParameterRequest(SetProcParameterRequest {
1068                server_id: None,
1069                username: None,
1070                password: Some(pw),
1071                tree_path: path,
1072                tree,
1073            }),
1074            Body::GetProfilePackRequest(profile),
1075            Body::GetProfileListRequest(profile),
1076        ];
1077        for body in bodies {
1078            let message = Message { transaction_id: b"t", group_no: 0, abort_on_error: 0, body };
1079            let shown = format!("{body:?} {message:?} {message:#?}");
1080            assert!(!shown.contains("hunter2") && !shown.contains("104, 117, 110"), "{shown}");
1081            assert!(shown.contains("<redacted>"), "{shown}");
1082            // Written and decoded again, the password is still redacted.
1083            let mut buf = [0u8; 256];
1084            let mut w = Writer::new(&mut buf);
1085            message.write(&mut w).unwrap();
1086            let n = w.position();
1087            let again = Message::read(&mut Reader::new(&buf[..n]), ParseOptions::default()).unwrap();
1088            assert_eq!(again, message);
1089            assert!(!format!("{again:?}").contains("104, 117, 110"));
1090        }
1091    }
1092
1093    // 001-real-meter-readiness/SR-006: no Debug output of a parser shows payload bytes.
1094    #[test]
1095    fn debug_of_parsers_never_prints_payload_bytes() {
1096        let payload = b"\x76secret-password";
1097        let shown = format!(
1098            "{:?} {:?} {:?}",
1099            Messages::new(payload, ParseOptions::default()),
1100            Reader::new(payload),
1101            crate::Decoder::new([0u8; 8])
1102        );
1103        assert!(!shown.contains("115, 101, 99") && !shown.contains("secret"), "{shown}");
1104    }
1105
1106    #[test]
1107    fn raw_parts_must_be_one_element_or_nothing_is_written() {
1108        let mut buf = [0u8; 64];
1109        for raw in [&[][..], &[0x01, 0x01], &[0x72, 0x01]] {
1110            let m = Message {
1111                transaction_id: b"t",
1112                group_no: 0,
1113                abort_on_error: 0,
1114                body: Body::Other { tag: 0x500, raw },
1115            };
1116            assert!(m.write(&mut Writer::new(&mut buf)).is_err(), "{raw:02x?}");
1117            let a =
1118                Attention { server_id: ServerId::new(b"s"), number: b"n", message: None, details: Some(raw) };
1119            let m = Message { body: Body::Attention(a), ..m };
1120            assert!(m.write(&mut Writer::new(&mut buf)).is_err(), "{raw:02x?}");
1121        }
1122    }
1123
1124    #[test]
1125    fn lists_compare_by_what_they_yield() {
1126        let dzg_meter: &[u8] = &[0x0a, 0x01, b'D', b'Z', b'G', 0, 2, 0x82, 0x22, 0x5e];
1127        let entries = [ListEntry::number(Obis::POWER, Unit::W, -2, -29_912)];
1128        let body = Body::GetListResponse(GetListResponse {
1129            client_id: None,
1130            server_id: ServerId::new(dzg_meter),
1131            list_name: None,
1132            act_sensor_time: None,
1133            entries: ListEntries::from_slice(&entries),
1134            list_signature: None,
1135            act_gateway_time: None,
1136        });
1137        let mut buf = [0u8; 128];
1138        let mut w = Writer::new(&mut buf);
1139        Message { transaction_id: b"t", group_no: 0, abort_on_error: 0, body }.write(&mut w).unwrap();
1140        let n = w.position();
1141        let plain = readout_with(&buf[..n], ParseOptions::default()).unwrap();
1142        let fixed = readout_with(&buf[..n], ParseOptions::default().with_dzg_power(true)).unwrap();
1143        let off =
1144            readout_with(&buf[..n], ParseOptions { crc: CrcCheck::Off, ..ParseOptions::default() }).unwrap();
1145        // Built and decoded lists are equal; the CRC mode does not matter, the DZG rule does.
1146        assert_eq!(plain.entries, ListEntries::from_slice(&entries));
1147        assert_eq!(plain.entries, off.entries);
1148        assert_ne!(plain.entries, fixed.entries);
1149        assert_eq!(format!("{:?}", plain.entries), "Seq { len: 1, .. }");
1150    }
1151
1152    #[test]
1153    fn dzg_correction_only_touches_short_negatives() {
1154        assert_eq!(dzg_unsigned(SmlValue::Int(0), 2), SmlValue::Int(0));
1155        assert_eq!(dzg_unsigned(SmlValue::Int(-29_912), 2), SmlValue::Uint(35_624));
1156        assert_eq!(dzg_unsigned(SmlValue::Int(-1), 1), SmlValue::Uint(255));
1157        assert_eq!(dzg_unsigned(SmlValue::Int(-1), 3), SmlValue::Uint(0xFF_FFFF));
1158        assert_eq!(dzg_unsigned(SmlValue::Int(-60_525), 4), SmlValue::Int(-60_525));
1159        assert_eq!(dzg_unsigned(SmlValue::Int(5), 2), SmlValue::Int(5));
1160        assert_eq!(dzg_unsigned(SmlValue::Uint(5), 2), SmlValue::Uint(5));
1161    }
1162}