sml-kit 0.1.2

Read German smart meters in Rust: SML (Smart Message Language) decoder and encoder, sans-I/O, no_std, no allocator, no dependencies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! The SML type-length encoding.
//!
//! Every SML value starts with one or more TL bytes:
//!
//! ```text
//!  bit   7     6 5 4     3 2 1 0
//!       more   type      length nibble
//! ```
//!
//! `type` is `000` octet string, `100` boolean, `101` integer, `110` unsigned, `111`
//! list. When `more` is set, another TL byte follows whose low nibble extends the
//! length (most significant nibble first) and whose type bits are zero.
//!
//! For a list the length is the number of elements. For every other type it is the
//! number of bytes **including the TL bytes themselves**, which is why `0x01` is an
//! empty octet string, the marker SML uses for an absent optional field. `0x00` is the
//! end-of-message marker, not a value.

use crate::{Error, Result};

/// The end-of-message marker.
pub const END_OF_MESSAGE: u8 = 0x00;
/// The marker for an absent optional field (an empty octet string).
pub const ABSENT: u8 = 0x01;
/// How deep [`Reader::skip`] follows nested lists before it gives up.
pub const MAX_DEPTH: u8 = 16;

/// The type of an SML value.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Kind {
    /// `000`: a byte string.
    OctetString,
    /// `100`: a boolean.
    Boolean,
    /// `101`: a two's-complement integer, big-endian.
    Integer,
    /// `110`: an unsigned integer, big-endian.
    Unsigned,
    /// `111`: a list of values.
    List,
}

impl Kind {
    const fn bits(self) -> u8 {
        match self {
            Self::OctetString => 0b000,
            Self::Boolean => 0b100,
            Self::Integer => 0b101,
            Self::Unsigned => 0b110,
            Self::List => 0b111,
        }
    }
}

/// A decoded type-length field.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Tl {
    /// The value's type.
    pub kind: Kind,
    /// For a list, the number of elements; otherwise the number of data bytes that
    /// follow the TL bytes.
    pub len: usize,
}

/// A cursor over SML bytes. Never allocates and never panics.
///
/// `Debug` shows the position and length, never the bytes: they may hold credentials.
#[derive(Clone)]
pub struct Reader<'a> {
    buf: &'a [u8],
    pos: usize,
}

impl core::fmt::Debug for Reader<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Reader").field("pos", &self.pos).field("len", &self.buf.len()).finish()
    }
}

impl<'a> Reader<'a> {
    /// A reader at the start of `buf`.
    pub const fn new(buf: &'a [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    /// Bytes consumed so far.
    pub const fn position(&self) -> usize {
        self.pos
    }

    /// Whether every byte has been consumed.
    pub const fn is_empty(&self) -> bool {
        self.pos >= self.buf.len()
    }

    /// The underlying buffer.
    pub const fn buffer(&self) -> &'a [u8] {
        self.buf
    }

    /// The next byte, without consuming it.
    pub fn peek(&self) -> Option<u8> {
        self.buf.get(self.pos).copied()
    }

    fn byte(&mut self) -> Result<u8> {
        let b = self.peek().ok_or(Error::UnexpectedEnd)?;
        self.pos += 1;
        Ok(b)
    }

    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
        let end = self.pos.checked_add(n).ok_or(Error::UnexpectedEnd)?;
        let s = self.buf.get(self.pos..end).ok_or(Error::UnexpectedEnd)?;
        self.pos = end;
        Ok(s)
    }

    /// The bytes between two positions of this reader.
    pub fn slice(&self, from: usize, to: usize) -> Result<&'a [u8]> {
        self.buf.get(from..to).ok_or(Error::UnexpectedEnd)
    }

    /// Consume the end-of-message byte.
    pub fn end_of_message(&mut self) -> Result<()> {
        match self.peek() {
            Some(END_OF_MESSAGE) => {
                self.pos += 1;
                Ok(())
            }
            Some(_) => Err(Error::MissingEndOfMessage),
            None => Err(Error::UnexpectedEnd),
        }
    }

    /// Consume an absent-field marker if one is next. Returns whether it was.
    pub fn absent(&mut self) -> bool {
        if self.peek() == Some(ABSENT) {
            self.pos += 1;
            true
        } else {
            false
        }
    }

    /// Read one type-length field.
    pub fn read_tl(&mut self) -> Result<Tl> {
        let first = self.byte()?;
        let kind = match (first >> 4) & 0b111 {
            0b000 => Kind::OctetString,
            0b100 => Kind::Boolean,
            0b101 => Kind::Integer,
            0b110 => Kind::Unsigned,
            0b111 => Kind::List,
            _ => return Err(Error::InvalidTl(first)),
        };
        let mut len = usize::from(first & 0x0F);
        let mut tl_bytes = 1usize;
        let mut b = first;
        while b & 0x80 != 0 {
            b = self.byte()?;
            if b & 0x70 != 0 {
                return Err(Error::InvalidTl(b));
            }
            tl_bytes += 1;
            if tl_bytes > 4 {
                return Err(Error::InvalidLength);
            }
            len = (len << 4) | usize::from(b & 0x0F);
        }
        if kind != Kind::List {
            len = len.checked_sub(tl_bytes).ok_or(Error::InvalidTl(first))?;
        }
        Ok(Tl { kind, len })
    }

    fn expect(&mut self, kind: Kind) -> Result<Tl> {
        let tl = self.read_tl()?;
        if tl.kind == kind { Ok(tl) } else { Err(Error::UnexpectedType { expected: kind, found: tl.kind }) }
    }

    /// Read a list header and require exactly `n` elements.
    pub fn list(&mut self, n: usize) -> Result<()> {
        let tl = self.expect(Kind::List)?;
        if tl.len == n { Ok(()) } else { Err(Error::ListLength { expected: n, found: tl.len }) }
    }

    /// Read a list header of any length and return the element count.
    pub fn list_any(&mut self) -> Result<usize> {
        Ok(self.expect(Kind::List)?.len)
    }

    /// Read an octet string. An absent marker reads as an empty string.
    pub fn octet_string(&mut self) -> Result<&'a [u8]> {
        let tl = self.expect(Kind::OctetString)?;
        self.take(tl.len)
    }

    /// Read an optional octet string.
    pub fn opt_octet_string(&mut self) -> Result<Option<&'a [u8]>> {
        if self.absent() { Ok(None) } else { self.octet_string().map(Some) }
    }

    /// Read a boolean.
    pub fn boolean(&mut self) -> Result<bool> {
        let tl = self.expect(Kind::Boolean)?;
        if tl.len != 1 {
            return Err(Error::InvalidLength);
        }
        Ok(self.byte()? != 0)
    }

    fn int_bytes(&mut self, tl: Tl) -> Result<&'a [u8]> {
        if tl.len == 0 || tl.len > 8 {
            return Err(Error::InvalidLength);
        }
        self.take(tl.len)
    }

    /// Read an unsigned integer of 1 to 8 bytes.
    pub fn unsigned(&mut self) -> Result<u64> {
        let tl = self.expect(Kind::Unsigned)?;
        let bytes = self.int_bytes(tl)?;
        Ok(bytes.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b)))
    }

    /// Read an optional unsigned integer.
    pub fn opt_unsigned(&mut self) -> Result<Option<u64>> {
        if self.absent() { Ok(None) } else { self.unsigned().map(Some) }
    }

    /// Read a signed integer of 1 to 8 bytes.
    pub fn integer(&mut self) -> Result<i64> {
        let tl = self.expect(Kind::Integer)?;
        let bytes = self.int_bytes(tl)?;
        Ok(sign_extend(bytes))
    }

    /// Read an optional signed integer.
    pub fn opt_integer(&mut self) -> Result<Option<i64>> {
        if self.absent() { Ok(None) } else { self.integer().map(Some) }
    }

    /// Skip one value of any type, following lists up to [`MAX_DEPTH`].
    pub fn skip(&mut self) -> Result<()> {
        self.skip_at(0)
    }

    fn skip_at(&mut self, depth: u8) -> Result<()> {
        if depth > MAX_DEPTH {
            return Err(Error::DepthLimit);
        }
        let tl = self.read_tl()?;
        if tl.kind == Kind::List {
            for _ in 0..tl.len {
                self.skip_at(depth + 1)?;
            }
        } else {
            self.take(tl.len)?;
        }
        Ok(())
    }
}

/// Sign-extend 1 to 8 big-endian bytes to an `i64`.
fn sign_extend(bytes: &[u8]) -> i64 {
    let negative = bytes.first().is_some_and(|b| b & 0x80 != 0);
    let start: u64 = if negative { u64::MAX } else { 0 };
    let raw = bytes.iter().fold(start, |acc, &b| (acc << 8) | u64::from(b));
    i64::from_be_bytes(raw.to_be_bytes())
}

/// A cursor that writes SML values into a caller-provided buffer.
///
/// Used by the tests and simulators; a meter readout client never needs it.
///
/// `Debug` shows the position and capacity, never the bytes.
pub struct Writer<'b> {
    buf: &'b mut [u8],
    pos: usize,
}

impl core::fmt::Debug for Writer<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Writer").field("pos", &self.pos).field("capacity", &self.buf.len()).finish()
    }
}

impl<'b> Writer<'b> {
    /// A writer at the start of `buf`.
    pub fn new(buf: &'b mut [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    /// Bytes written so far.
    pub const fn position(&self) -> usize {
        self.pos
    }

    /// The bytes written so far.
    pub fn written(&self) -> &[u8] {
        self.buf.get(..self.pos).unwrap_or(&[])
    }

    /// Write raw bytes.
    pub fn raw(&mut self, bytes: &[u8]) -> Result<()> {
        let end = self.pos.checked_add(bytes.len()).ok_or(Error::OutputTooSmall)?;
        self.buf.get_mut(self.pos..end).ok_or(Error::OutputTooSmall)?.copy_from_slice(bytes);
        self.pos = end;
        Ok(())
    }

    /// Write a type-length field. `len` is the element count for a list and the number
    /// of data bytes otherwise.
    pub fn tl(&mut self, kind: Kind, len: usize) -> Result<()> {
        for n in 1..=4usize {
            let total =
                if kind == Kind::List { len } else { len.checked_add(n).ok_or(Error::InvalidLength)? };
            if total < 1 << (4 * n) {
                let mut out = [0u8; 4];
                for (i, slot) in out.iter_mut().enumerate().take(n) {
                    let nibble = u8::try_from((total >> (4 * (n - 1 - i))) & 0x0F).unwrap_or(0);
                    let more = if i + 1 < n { 0x80 } else { 0 };
                    let type_bits = if i == 0 { kind.bits() << 4 } else { 0 };
                    *slot = more | type_bits | nibble;
                }
                return self.raw(out.get(..n).unwrap_or(&[]));
            }
        }
        Err(Error::InvalidLength)
    }

    /// Write a list header.
    pub fn list(&mut self, n: usize) -> Result<()> {
        self.tl(Kind::List, n)
    }

    /// Write an octet string.
    pub fn octet_string(&mut self, bytes: &[u8]) -> Result<()> {
        self.tl(Kind::OctetString, bytes.len())?;
        self.raw(bytes)
    }

    /// Write the absent-field marker.
    pub fn absent(&mut self) -> Result<()> {
        self.raw(&[ABSENT])
    }

    /// Write a boolean.
    pub fn boolean(&mut self, v: bool) -> Result<()> {
        self.tl(Kind::Boolean, 1)?;
        self.raw(&[u8::from(v)])
    }

    /// Write an unsigned integer in exactly `width` bytes (1, 2, 4 or 8 for the SML
    /// types `Unsigned8` to `Unsigned64`).
    pub fn unsigned(&mut self, v: u64, width: usize) -> Result<()> {
        if !(1..=8).contains(&width) || (width < 8 && v >> (8 * width) != 0) {
            return Err(Error::ValueOutOfRange);
        }
        self.tl(Kind::Unsigned, width)?;
        let be = v.to_be_bytes();
        self.raw(be.get(8 - width..).unwrap_or(&[]))
    }

    /// Write a signed integer in exactly `width` bytes.
    pub fn integer(&mut self, v: i64, width: usize) -> Result<()> {
        if !(1..=8).contains(&width) {
            return Err(Error::ValueOutOfRange);
        }
        let bits = 8 * u32::try_from(width).unwrap_or(8);
        if width < 8 && (v < -(1i64 << (bits - 1)) || v >= 1i64 << (bits - 1)) {
            return Err(Error::ValueOutOfRange);
        }
        self.tl(Kind::Integer, width)?;
        let be = v.to_be_bytes();
        self.raw(be.get(8 - width..).unwrap_or(&[]))
    }

    /// Write an unsigned integer in the smallest of 1, 2, 4 or 8 bytes that holds it.
    pub fn unsigned_min(&mut self, v: u64) -> Result<()> {
        let width = [1usize, 2, 4].into_iter().find(|&w| v >> (8 * w) == 0).unwrap_or(8);
        self.unsigned(v, width)
    }

    /// Write a signed integer in the smallest of 1, 2, 4 or 8 bytes that holds it.
    pub fn integer_min(&mut self, v: i64) -> Result<()> {
        let width = [1usize, 2, 4]
            .into_iter()
            .find(|&w| {
                let half = 1i64 << (8 * w - 1);
                (-half..half).contains(&v)
            })
            .unwrap_or(8);
        self.integer(v, width)
    }

    /// Write an optional octet string: the absent marker for `None`.
    pub fn opt_octet_string(&mut self, bytes: Option<&[u8]>) -> Result<()> {
        match bytes {
            Some(b) => self.octet_string(b),
            None => self.absent(),
        }
    }

    /// Write the end-of-message marker.
    pub fn end_of_message(&mut self) -> Result<()> {
        self.raw(&[END_OF_MESSAGE])
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn single_byte_tl() {
        let mut r = Reader::new(&[0x07, 1, 0, 1, 8, 0, 0xFF]);
        assert_eq!(r.octet_string().unwrap(), &[1, 0, 1, 8, 0, 0xFF]);
        assert!(r.is_empty());
    }

    #[test]
    fn absent_is_an_empty_octet_string() {
        let mut r = Reader::new(&[0x01, 0x01]);
        assert_eq!(r.opt_octet_string().unwrap(), None);
        assert_eq!(r.octet_string().unwrap(), &[] as &[u8]);
    }

    #[test]
    fn multi_byte_tl_round_trips() {
        let data = [0xAB; 40];
        let mut buf = [0u8; 64];
        let mut w = Writer::new(&mut buf);
        w.octet_string(&data).unwrap();
        let n = w.position();
        // 40 data bytes + 2 TL bytes = 42 = 0x2A: TL bytes 0x82 0x0A.
        assert_eq!(buf.get(..2).unwrap(), &[0x82, 0x0A]);
        let mut r = Reader::new(buf.get(..n).unwrap());
        assert_eq!(r.octet_string().unwrap(), &data);
    }

    #[test]
    fn long_list_header() {
        let mut buf = [0u8; 4];
        let mut w = Writer::new(&mut buf);
        w.list(0x16).unwrap();
        assert_eq!(w.written(), &[0xF1, 0x06]);
        assert_eq!(Reader::new(&[0xF1, 0x06]).list_any().unwrap(), 0x16);
    }

    #[test]
    fn integers_sign_extend() {
        let mut r =
            Reader::new(&[0x52, 0xFF, 0x53, 0x80, 0x00, 0x62, 0x1E, 0x59, 0, 0, 0, 0, 0, 0, 0x30, 0x39]);
        assert_eq!(r.integer().unwrap(), -1);
        assert_eq!(r.integer().unwrap(), -32768);
        assert_eq!(r.unsigned().unwrap(), 30);
        assert_eq!(r.integer().unwrap(), 12345);
    }

    #[test]
    fn odd_widths_are_accepted() {
        // Meters use 3-, 5- and 7-byte integers in practice.
        let mut r = Reader::new(&[0x64, 0x01, 0x02, 0x03]);
        assert_eq!(r.unsigned().unwrap(), 0x0001_0203);
    }

    #[test]
    fn malformed_input_is_an_error_not_a_panic() {
        for input in [&[0x00][..], &[0x10], &[0x82], &[0x82, 0x10], &[0x07, 1, 2], &[0x60], &[0x6A, 0, 0]] {
            let mut r = Reader::new(input);
            assert!(r.skip().is_err(), "{input:02x?}");
        }
    }

    #[test]
    fn deep_nesting_is_bounded() {
        // 16 nested lists around a value is the limit; one more is an error.
        let mut ok = [0x71u8; 17];
        ok[16] = 0x01;
        assert_eq!(Reader::new(&ok).skip(), Ok(()));
        let mut deep = [0x71u8; 18];
        deep[17] = 0x01;
        assert_eq!(Reader::new(&deep).skip(), Err(Error::DepthLimit));
        let input = [0x71u8; 64];
        assert_eq!(Reader::new(&input).skip(), Err(Error::DepthLimit));
    }

    #[test]
    fn writer_rejects_values_that_do_not_fit() {
        let mut buf = [0u8; 16];
        let mut w = Writer::new(&mut buf);
        assert_eq!(w.integer(-129, 1), Err(Error::ValueOutOfRange));
        assert_eq!(w.integer(-32_769, 2), Err(Error::ValueOutOfRange));
        assert!(w.integer(-32_768, 2).is_ok());
        let mut buf = [0u8; 16];
        let mut w = Writer::new(&mut buf);
        assert_eq!(w.unsigned(256, 1), Err(Error::ValueOutOfRange));
        assert_eq!(w.integer(128, 1), Err(Error::ValueOutOfRange));
        assert!(w.integer(-128, 1).is_ok());
    }

    #[test]
    fn tl_fields_of_up_to_four_bytes() {
        // A 4-byte TL: octet string of 0x1000 total bytes, here only its header.
        let mut r = Reader::new(&[0x81, 0x80, 0x80, 0x04]);
        assert_eq!(r.read_tl(), Ok(Tl { kind: Kind::OctetString, len: 0x1004 - 4 }));
        assert_eq!(Reader::new(&[0x81, 0x80, 0x80, 0x80, 0x05]).read_tl(), Err(Error::InvalidLength));
        // 15 data bytes need 16 in total: two TL bytes.
        let mut buf = [0u8; 32];
        let mut w = Writer::new(&mut buf);
        w.octet_string(&[9; 15]).unwrap();
        assert_eq!(&buf[..2], &[0x81, 0x01]);
        assert_eq!(Reader::new(&buf).octet_string().unwrap(), &[9; 15]);
        let mut w = Writer::new(&mut buf);
        w.octet_string(&[9; 14]).unwrap();
        assert_eq!(buf[0], 0x0F);
    }

    #[test]
    fn an_integer_without_bytes_is_an_error() {
        assert_eq!(Reader::new(&[0x61]).unsigned(), Err(Error::InvalidLength));
        assert_eq!(Reader::new(&[0x51]).integer(), Err(Error::InvalidLength));
        assert_eq!(Reader::new(&[0x6A, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unsigned(), Err(Error::InvalidLength));
    }

    #[test]
    fn debug_shows_positions_not_bytes() {
        extern crate std;
        let r = Reader::new(&[1, 2, 3]);
        assert_eq!(std::format!("{r:?}"), "Reader { pos: 0, len: 3 }");
        let mut buf = [0u8; 4];
        let w = Writer::new(&mut buf);
        assert_eq!(std::format!("{w:?}"), "Writer { pos: 0, capacity: 4 }");
    }

    #[test]
    fn minimal_widths() {
        for (v, tl) in [(0u64, 0x62), (255, 0x62), (256, 0x63), (65_536, 0x65), (u64::MAX, 0x69)] {
            let mut buf = [0u8; 16];
            let mut w = Writer::new(&mut buf);
            w.unsigned_min(v).unwrap();
            assert_eq!(buf[0], tl, "{v}");
            assert_eq!(Reader::new(&buf).unsigned().unwrap(), v);
        }
        for (v, tl) in [(-128i64, 0x52), (127, 0x52), (128, 0x53), (-32_769, 0x55), (i64::MIN, 0x59)] {
            let mut buf = [0u8; 16];
            let mut w = Writer::new(&mut buf);
            w.integer_min(v).unwrap();
            assert_eq!(buf[0], tl, "{v}");
            assert_eq!(Reader::new(&buf).integer().unwrap(), v);
        }
    }
}