Skip to main content

sml_kit/
tl.rs

1//! The SML type-length encoding.
2//!
3//! Every SML value starts with one or more TL bytes:
4//!
5//! ```text
6//!  bit   7     6 5 4     3 2 1 0
7//!       more   type      length nibble
8//! ```
9//!
10//! `type` is `000` octet string, `100` boolean, `101` integer, `110` unsigned, `111`
11//! list. When `more` is set, another TL byte follows whose low nibble extends the
12//! length (most significant nibble first) and whose type bits are zero.
13//!
14//! For a list the length is the number of elements. For every other type it is the
15//! number of bytes **including the TL bytes themselves**, which is why `0x01` is an
16//! empty octet string, the marker SML uses for an absent optional field. `0x00` is the
17//! end-of-message marker, not a value.
18
19use crate::{Error, Result};
20
21/// The end-of-message marker.
22pub const END_OF_MESSAGE: u8 = 0x00;
23/// The marker for an absent optional field (an empty octet string).
24pub const ABSENT: u8 = 0x01;
25/// How deep [`Reader::skip`] follows nested lists before it gives up.
26pub const MAX_DEPTH: u8 = 16;
27
28/// The type of an SML value.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
30pub enum Kind {
31    /// `000`: a byte string.
32    OctetString,
33    /// `100`: a boolean.
34    Boolean,
35    /// `101`: a two's-complement integer, big-endian.
36    Integer,
37    /// `110`: an unsigned integer, big-endian.
38    Unsigned,
39    /// `111`: a list of values.
40    List,
41}
42
43impl Kind {
44    const fn bits(self) -> u8 {
45        match self {
46            Self::OctetString => 0b000,
47            Self::Boolean => 0b100,
48            Self::Integer => 0b101,
49            Self::Unsigned => 0b110,
50            Self::List => 0b111,
51        }
52    }
53}
54
55/// A decoded type-length field.
56#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
57pub struct Tl {
58    /// The value's type.
59    pub kind: Kind,
60    /// For a list, the number of elements; otherwise the number of data bytes that
61    /// follow the TL bytes.
62    pub len: usize,
63}
64
65/// A cursor over SML bytes. Never allocates and never panics.
66///
67/// `Debug` shows the position and length, never the bytes: they may hold credentials.
68#[derive(Clone)]
69pub struct Reader<'a> {
70    buf: &'a [u8],
71    pos: usize,
72}
73
74impl core::fmt::Debug for Reader<'_> {
75    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
76        f.debug_struct("Reader").field("pos", &self.pos).field("len", &self.buf.len()).finish()
77    }
78}
79
80impl<'a> Reader<'a> {
81    /// A reader at the start of `buf`.
82    pub const fn new(buf: &'a [u8]) -> Self {
83        Self { buf, pos: 0 }
84    }
85
86    /// Bytes consumed so far.
87    pub const fn position(&self) -> usize {
88        self.pos
89    }
90
91    /// Whether every byte has been consumed.
92    pub const fn is_empty(&self) -> bool {
93        self.pos >= self.buf.len()
94    }
95
96    /// The underlying buffer.
97    pub const fn buffer(&self) -> &'a [u8] {
98        self.buf
99    }
100
101    /// The next byte, without consuming it.
102    pub fn peek(&self) -> Option<u8> {
103        self.buf.get(self.pos).copied()
104    }
105
106    fn byte(&mut self) -> Result<u8> {
107        let b = self.peek().ok_or(Error::UnexpectedEnd)?;
108        self.pos += 1;
109        Ok(b)
110    }
111
112    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
113        let end = self.pos.checked_add(n).ok_or(Error::UnexpectedEnd)?;
114        let s = self.buf.get(self.pos..end).ok_or(Error::UnexpectedEnd)?;
115        self.pos = end;
116        Ok(s)
117    }
118
119    /// The bytes between two positions of this reader.
120    pub fn slice(&self, from: usize, to: usize) -> Result<&'a [u8]> {
121        self.buf.get(from..to).ok_or(Error::UnexpectedEnd)
122    }
123
124    /// Consume the end-of-message byte.
125    pub fn end_of_message(&mut self) -> Result<()> {
126        match self.peek() {
127            Some(END_OF_MESSAGE) => {
128                self.pos += 1;
129                Ok(())
130            }
131            Some(_) => Err(Error::MissingEndOfMessage),
132            None => Err(Error::UnexpectedEnd),
133        }
134    }
135
136    /// Consume an absent-field marker if one is next. Returns whether it was.
137    pub fn absent(&mut self) -> bool {
138        if self.peek() == Some(ABSENT) {
139            self.pos += 1;
140            true
141        } else {
142            false
143        }
144    }
145
146    /// Read one type-length field.
147    pub fn read_tl(&mut self) -> Result<Tl> {
148        let first = self.byte()?;
149        let kind = match (first >> 4) & 0b111 {
150            0b000 => Kind::OctetString,
151            0b100 => Kind::Boolean,
152            0b101 => Kind::Integer,
153            0b110 => Kind::Unsigned,
154            0b111 => Kind::List,
155            _ => return Err(Error::InvalidTl(first)),
156        };
157        let mut len = usize::from(first & 0x0F);
158        let mut tl_bytes = 1usize;
159        let mut b = first;
160        while b & 0x80 != 0 {
161            b = self.byte()?;
162            if b & 0x70 != 0 {
163                return Err(Error::InvalidTl(b));
164            }
165            tl_bytes += 1;
166            if tl_bytes > 4 {
167                return Err(Error::InvalidLength);
168            }
169            len = (len << 4) | usize::from(b & 0x0F);
170        }
171        if kind != Kind::List {
172            len = len.checked_sub(tl_bytes).ok_or(Error::InvalidTl(first))?;
173        }
174        Ok(Tl { kind, len })
175    }
176
177    fn expect(&mut self, kind: Kind) -> Result<Tl> {
178        let tl = self.read_tl()?;
179        if tl.kind == kind { Ok(tl) } else { Err(Error::UnexpectedType { expected: kind, found: tl.kind }) }
180    }
181
182    /// Read a list header and require exactly `n` elements.
183    pub fn list(&mut self, n: usize) -> Result<()> {
184        let tl = self.expect(Kind::List)?;
185        if tl.len == n { Ok(()) } else { Err(Error::ListLength { expected: n, found: tl.len }) }
186    }
187
188    /// Read a list header of any length and return the element count.
189    pub fn list_any(&mut self) -> Result<usize> {
190        Ok(self.expect(Kind::List)?.len)
191    }
192
193    /// Read an octet string. An absent marker reads as an empty string.
194    pub fn octet_string(&mut self) -> Result<&'a [u8]> {
195        let tl = self.expect(Kind::OctetString)?;
196        self.take(tl.len)
197    }
198
199    /// Read an optional octet string.
200    pub fn opt_octet_string(&mut self) -> Result<Option<&'a [u8]>> {
201        if self.absent() { Ok(None) } else { self.octet_string().map(Some) }
202    }
203
204    /// Read a boolean.
205    pub fn boolean(&mut self) -> Result<bool> {
206        let tl = self.expect(Kind::Boolean)?;
207        if tl.len != 1 {
208            return Err(Error::InvalidLength);
209        }
210        Ok(self.byte()? != 0)
211    }
212
213    fn int_bytes(&mut self, tl: Tl) -> Result<&'a [u8]> {
214        if tl.len == 0 || tl.len > 8 {
215            return Err(Error::InvalidLength);
216        }
217        self.take(tl.len)
218    }
219
220    /// Read an unsigned integer of 1 to 8 bytes.
221    pub fn unsigned(&mut self) -> Result<u64> {
222        let tl = self.expect(Kind::Unsigned)?;
223        let bytes = self.int_bytes(tl)?;
224        Ok(bytes.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b)))
225    }
226
227    /// Read an optional unsigned integer.
228    pub fn opt_unsigned(&mut self) -> Result<Option<u64>> {
229        if self.absent() { Ok(None) } else { self.unsigned().map(Some) }
230    }
231
232    /// Read a signed integer of 1 to 8 bytes.
233    pub fn integer(&mut self) -> Result<i64> {
234        let tl = self.expect(Kind::Integer)?;
235        let bytes = self.int_bytes(tl)?;
236        Ok(sign_extend(bytes))
237    }
238
239    /// Read an optional signed integer.
240    pub fn opt_integer(&mut self) -> Result<Option<i64>> {
241        if self.absent() { Ok(None) } else { self.integer().map(Some) }
242    }
243
244    /// Skip one value of any type, following lists up to [`MAX_DEPTH`].
245    pub fn skip(&mut self) -> Result<()> {
246        self.skip_at(0)
247    }
248
249    fn skip_at(&mut self, depth: u8) -> Result<()> {
250        if depth > MAX_DEPTH {
251            return Err(Error::DepthLimit);
252        }
253        let tl = self.read_tl()?;
254        if tl.kind == Kind::List {
255            for _ in 0..tl.len {
256                self.skip_at(depth + 1)?;
257            }
258        } else {
259            self.take(tl.len)?;
260        }
261        Ok(())
262    }
263}
264
265/// Sign-extend 1 to 8 big-endian bytes to an `i64`.
266fn sign_extend(bytes: &[u8]) -> i64 {
267    let negative = bytes.first().is_some_and(|b| b & 0x80 != 0);
268    let start: u64 = if negative { u64::MAX } else { 0 };
269    let raw = bytes.iter().fold(start, |acc, &b| (acc << 8) | u64::from(b));
270    i64::from_be_bytes(raw.to_be_bytes())
271}
272
273/// A cursor that writes SML values into a caller-provided buffer.
274///
275/// Used by the tests and simulators; a meter readout client never needs it.
276///
277/// `Debug` shows the position and capacity, never the bytes.
278pub struct Writer<'b> {
279    buf: &'b mut [u8],
280    pos: usize,
281}
282
283impl core::fmt::Debug for Writer<'_> {
284    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
285        f.debug_struct("Writer").field("pos", &self.pos).field("capacity", &self.buf.len()).finish()
286    }
287}
288
289impl<'b> Writer<'b> {
290    /// A writer at the start of `buf`.
291    pub fn new(buf: &'b mut [u8]) -> Self {
292        Self { buf, pos: 0 }
293    }
294
295    /// Bytes written so far.
296    pub const fn position(&self) -> usize {
297        self.pos
298    }
299
300    /// The bytes written so far.
301    pub fn written(&self) -> &[u8] {
302        self.buf.get(..self.pos).unwrap_or(&[])
303    }
304
305    /// Write raw bytes.
306    pub fn raw(&mut self, bytes: &[u8]) -> Result<()> {
307        let end = self.pos.checked_add(bytes.len()).ok_or(Error::OutputTooSmall)?;
308        self.buf.get_mut(self.pos..end).ok_or(Error::OutputTooSmall)?.copy_from_slice(bytes);
309        self.pos = end;
310        Ok(())
311    }
312
313    /// Write a type-length field. `len` is the element count for a list and the number
314    /// of data bytes otherwise.
315    pub fn tl(&mut self, kind: Kind, len: usize) -> Result<()> {
316        for n in 1..=4usize {
317            let total =
318                if kind == Kind::List { len } else { len.checked_add(n).ok_or(Error::InvalidLength)? };
319            if total < 1 << (4 * n) {
320                let mut out = [0u8; 4];
321                for (i, slot) in out.iter_mut().enumerate().take(n) {
322                    let nibble = u8::try_from((total >> (4 * (n - 1 - i))) & 0x0F).unwrap_or(0);
323                    let more = if i + 1 < n { 0x80 } else { 0 };
324                    let type_bits = if i == 0 { kind.bits() << 4 } else { 0 };
325                    *slot = more | type_bits | nibble;
326                }
327                return self.raw(out.get(..n).unwrap_or(&[]));
328            }
329        }
330        Err(Error::InvalidLength)
331    }
332
333    /// Write a list header.
334    pub fn list(&mut self, n: usize) -> Result<()> {
335        self.tl(Kind::List, n)
336    }
337
338    /// Write an octet string.
339    pub fn octet_string(&mut self, bytes: &[u8]) -> Result<()> {
340        self.tl(Kind::OctetString, bytes.len())?;
341        self.raw(bytes)
342    }
343
344    /// Write the absent-field marker.
345    pub fn absent(&mut self) -> Result<()> {
346        self.raw(&[ABSENT])
347    }
348
349    /// Write a boolean.
350    pub fn boolean(&mut self, v: bool) -> Result<()> {
351        self.tl(Kind::Boolean, 1)?;
352        self.raw(&[u8::from(v)])
353    }
354
355    /// Write an unsigned integer in exactly `width` bytes (1, 2, 4 or 8 for the SML
356    /// types `Unsigned8` to `Unsigned64`).
357    pub fn unsigned(&mut self, v: u64, width: usize) -> Result<()> {
358        if !(1..=8).contains(&width) || (width < 8 && v >> (8 * width) != 0) {
359            return Err(Error::ValueOutOfRange);
360        }
361        self.tl(Kind::Unsigned, width)?;
362        let be = v.to_be_bytes();
363        self.raw(be.get(8 - width..).unwrap_or(&[]))
364    }
365
366    /// Write a signed integer in exactly `width` bytes.
367    pub fn integer(&mut self, v: i64, width: usize) -> Result<()> {
368        if !(1..=8).contains(&width) {
369            return Err(Error::ValueOutOfRange);
370        }
371        let bits = 8 * u32::try_from(width).unwrap_or(8);
372        if width < 8 && (v < -(1i64 << (bits - 1)) || v >= 1i64 << (bits - 1)) {
373            return Err(Error::ValueOutOfRange);
374        }
375        self.tl(Kind::Integer, width)?;
376        let be = v.to_be_bytes();
377        self.raw(be.get(8 - width..).unwrap_or(&[]))
378    }
379
380    /// Write an unsigned integer in the smallest of 1, 2, 4 or 8 bytes that holds it.
381    pub fn unsigned_min(&mut self, v: u64) -> Result<()> {
382        let width = [1usize, 2, 4].into_iter().find(|&w| v >> (8 * w) == 0).unwrap_or(8);
383        self.unsigned(v, width)
384    }
385
386    /// Write a signed integer in the smallest of 1, 2, 4 or 8 bytes that holds it.
387    pub fn integer_min(&mut self, v: i64) -> Result<()> {
388        let width = [1usize, 2, 4]
389            .into_iter()
390            .find(|&w| {
391                let half = 1i64 << (8 * w - 1);
392                (-half..half).contains(&v)
393            })
394            .unwrap_or(8);
395        self.integer(v, width)
396    }
397
398    /// Write an optional octet string: the absent marker for `None`.
399    pub fn opt_octet_string(&mut self, bytes: Option<&[u8]>) -> Result<()> {
400        match bytes {
401            Some(b) => self.octet_string(b),
402            None => self.absent(),
403        }
404    }
405
406    /// Write the end-of-message marker.
407    pub fn end_of_message(&mut self) -> Result<()> {
408        self.raw(&[END_OF_MESSAGE])
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    #[test]
417    fn single_byte_tl() {
418        let mut r = Reader::new(&[0x07, 1, 0, 1, 8, 0, 0xFF]);
419        assert_eq!(r.octet_string().unwrap(), &[1, 0, 1, 8, 0, 0xFF]);
420        assert!(r.is_empty());
421    }
422
423    #[test]
424    fn absent_is_an_empty_octet_string() {
425        let mut r = Reader::new(&[0x01, 0x01]);
426        assert_eq!(r.opt_octet_string().unwrap(), None);
427        assert_eq!(r.octet_string().unwrap(), &[] as &[u8]);
428    }
429
430    #[test]
431    fn multi_byte_tl_round_trips() {
432        let data = [0xAB; 40];
433        let mut buf = [0u8; 64];
434        let mut w = Writer::new(&mut buf);
435        w.octet_string(&data).unwrap();
436        let n = w.position();
437        // 40 data bytes + 2 TL bytes = 42 = 0x2A: TL bytes 0x82 0x0A.
438        assert_eq!(buf.get(..2).unwrap(), &[0x82, 0x0A]);
439        let mut r = Reader::new(buf.get(..n).unwrap());
440        assert_eq!(r.octet_string().unwrap(), &data);
441    }
442
443    #[test]
444    fn long_list_header() {
445        let mut buf = [0u8; 4];
446        let mut w = Writer::new(&mut buf);
447        w.list(0x16).unwrap();
448        assert_eq!(w.written(), &[0xF1, 0x06]);
449        assert_eq!(Reader::new(&[0xF1, 0x06]).list_any().unwrap(), 0x16);
450    }
451
452    #[test]
453    fn integers_sign_extend() {
454        let mut r =
455            Reader::new(&[0x52, 0xFF, 0x53, 0x80, 0x00, 0x62, 0x1E, 0x59, 0, 0, 0, 0, 0, 0, 0x30, 0x39]);
456        assert_eq!(r.integer().unwrap(), -1);
457        assert_eq!(r.integer().unwrap(), -32768);
458        assert_eq!(r.unsigned().unwrap(), 30);
459        assert_eq!(r.integer().unwrap(), 12345);
460    }
461
462    #[test]
463    fn odd_widths_are_accepted() {
464        // Meters use 3-, 5- and 7-byte integers in practice.
465        let mut r = Reader::new(&[0x64, 0x01, 0x02, 0x03]);
466        assert_eq!(r.unsigned().unwrap(), 0x0001_0203);
467    }
468
469    #[test]
470    fn malformed_input_is_an_error_not_a_panic() {
471        for input in [&[0x00][..], &[0x10], &[0x82], &[0x82, 0x10], &[0x07, 1, 2], &[0x60], &[0x6A, 0, 0]] {
472            let mut r = Reader::new(input);
473            assert!(r.skip().is_err(), "{input:02x?}");
474        }
475    }
476
477    #[test]
478    fn deep_nesting_is_bounded() {
479        // 16 nested lists around a value is the limit; one more is an error.
480        let mut ok = [0x71u8; 17];
481        ok[16] = 0x01;
482        assert_eq!(Reader::new(&ok).skip(), Ok(()));
483        let mut deep = [0x71u8; 18];
484        deep[17] = 0x01;
485        assert_eq!(Reader::new(&deep).skip(), Err(Error::DepthLimit));
486        let input = [0x71u8; 64];
487        assert_eq!(Reader::new(&input).skip(), Err(Error::DepthLimit));
488    }
489
490    #[test]
491    fn writer_rejects_values_that_do_not_fit() {
492        let mut buf = [0u8; 16];
493        let mut w = Writer::new(&mut buf);
494        assert_eq!(w.integer(-129, 1), Err(Error::ValueOutOfRange));
495        assert_eq!(w.integer(-32_769, 2), Err(Error::ValueOutOfRange));
496        assert!(w.integer(-32_768, 2).is_ok());
497        let mut buf = [0u8; 16];
498        let mut w = Writer::new(&mut buf);
499        assert_eq!(w.unsigned(256, 1), Err(Error::ValueOutOfRange));
500        assert_eq!(w.integer(128, 1), Err(Error::ValueOutOfRange));
501        assert!(w.integer(-128, 1).is_ok());
502    }
503
504    #[test]
505    fn tl_fields_of_up_to_four_bytes() {
506        // A 4-byte TL: octet string of 0x1000 total bytes, here only its header.
507        let mut r = Reader::new(&[0x81, 0x80, 0x80, 0x04]);
508        assert_eq!(r.read_tl(), Ok(Tl { kind: Kind::OctetString, len: 0x1004 - 4 }));
509        assert_eq!(Reader::new(&[0x81, 0x80, 0x80, 0x80, 0x05]).read_tl(), Err(Error::InvalidLength));
510        // 15 data bytes need 16 in total: two TL bytes.
511        let mut buf = [0u8; 32];
512        let mut w = Writer::new(&mut buf);
513        w.octet_string(&[9; 15]).unwrap();
514        assert_eq!(&buf[..2], &[0x81, 0x01]);
515        assert_eq!(Reader::new(&buf).octet_string().unwrap(), &[9; 15]);
516        let mut w = Writer::new(&mut buf);
517        w.octet_string(&[9; 14]).unwrap();
518        assert_eq!(buf[0], 0x0F);
519    }
520
521    #[test]
522    fn an_integer_without_bytes_is_an_error() {
523        assert_eq!(Reader::new(&[0x61]).unsigned(), Err(Error::InvalidLength));
524        assert_eq!(Reader::new(&[0x51]).integer(), Err(Error::InvalidLength));
525        assert_eq!(Reader::new(&[0x6A, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unsigned(), Err(Error::InvalidLength));
526    }
527
528    #[test]
529    fn debug_shows_positions_not_bytes() {
530        extern crate std;
531        let r = Reader::new(&[1, 2, 3]);
532        assert_eq!(std::format!("{r:?}"), "Reader { pos: 0, len: 3 }");
533        let mut buf = [0u8; 4];
534        let w = Writer::new(&mut buf);
535        assert_eq!(std::format!("{w:?}"), "Writer { pos: 0, capacity: 4 }");
536    }
537
538    #[test]
539    fn minimal_widths() {
540        for (v, tl) in [(0u64, 0x62), (255, 0x62), (256, 0x63), (65_536, 0x65), (u64::MAX, 0x69)] {
541            let mut buf = [0u8; 16];
542            let mut w = Writer::new(&mut buf);
543            w.unsigned_min(v).unwrap();
544            assert_eq!(buf[0], tl, "{v}");
545            assert_eq!(Reader::new(&buf).unsigned().unwrap(), v);
546        }
547        for (v, tl) in [(-128i64, 0x52), (127, 0x52), (128, 0x53), (-32_769, 0x55), (i64::MIN, 0x59)] {
548            let mut buf = [0u8; 16];
549            let mut w = Writer::new(&mut buf);
550            w.integer_min(v).unwrap();
551            assert_eq!(buf[0], tl, "{v}");
552            assert_eq!(Reader::new(&buf).integer().unwrap(), v);
553        }
554    }
555}