sml-kit 0.1.0

SML (Smart Message Language) for Rust: German smart meter readout with a sans-I/O, no_std, allocation-free core
Documentation
//! `SEQUENCE OF …` without allocation: a list that is either encoded bytes from a frame,
//! parsed one element at a time, or a borrowed slice built for writing.

use core::fmt;

use crate::Result;
use crate::message::ParseOptions;
use crate::tl::{Reader, Writer};

/// How the elements of an encoded sequence are read: the options of the message they
/// came in, and whether the DZG power correction applies to this list.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, Default)]
pub struct Ctx {
    pub(crate) options: ParseOptions,
    pub(crate) dzg: bool,
}

impl Ctx {
    pub(crate) const fn new(options: ParseOptions) -> Self {
        Self { options, dzg: false }
    }
}

pub(crate) mod sealed {
    pub trait Sealed {}
}

/// An element of a [`Seq`]: [`ListEntry`](crate::ListEntry),
/// [`PeriodEntry`](crate::PeriodEntry), [`Tree`](crate::Tree) or a name (`&[u8]`).
/// Sealed: the encoding of each is fixed by the specification.
pub trait Element<'a>: Sized + Copy + PartialEq + sealed::Sealed {
    #[doc(hidden)]
    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self>;
    #[doc(hidden)]
    fn write(&self, w: &mut Writer<'_>) -> Result<()>;
}

impl sealed::Sealed for &[u8] {}
impl sealed::Sealed for crate::ListEntry<'_> {}
impl sealed::Sealed for crate::PeriodEntry<'_> {}
impl sealed::Sealed for crate::Tree<'_> {}

/// A name: an octet string, as in a tree path or a profile's object list.
impl<'a> Element<'a> for &'a [u8] {
    fn read(r: &mut Reader<'a>, _: Ctx) -> Result<Self> {
        r.octet_string()
    }

    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        w.octet_string(self)
    }
}

/// An SML `SEQUENCE OF T`, parsed lazily.
///
/// A sequence read from a frame keeps its encoded bytes and parses each element when
/// iterated; one built for writing borrows a slice. Both behave the same, and a built
/// sequence equals the decoded one:
///
/// ```
/// use sml_kit::{ListEntries, ListEntry, Obis, Unit};
///
/// let entries = [ListEntry::number(Obis::POWER, Unit::W, 0, 1337)];
/// let list = ListEntries::from_slice(&entries);
/// assert_eq!(list.len(), 1);
/// assert_eq!(list.iter().next(), Some(Ok(entries[0])));
/// ```
///
/// `Debug` shows only the length: the bytes of a request may hold credentials.
pub struct Seq<'a, T> {
    repr: Repr<'a, T>,
}

enum Repr<'a, T> {
    Encoded { raw: &'a [u8], count: usize, ctx: Ctx },
    Slice(&'a [T]),
}

impl<T> Clone for Repr<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for Repr<'_, T> {}

impl<T> Clone for Seq<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for Seq<'_, T> {}

impl<'a, T> Seq<'a, T> {
    /// A sequence of `items`, for writing.
    pub const fn from_slice(items: &'a [T]) -> Self {
        Self { repr: Repr::Slice(items) }
    }

    /// How many elements the sequence has (for an encoded one: declares).
    pub const fn len(&self) -> usize {
        match self.repr {
            Repr::Encoded { count, .. } => count,
            Repr::Slice(items) => items.len(),
        }
    }

    /// Whether the sequence is empty.
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<'a, T: Element<'a>> Seq<'a, T> {
    /// The elements, one at a time. An encoded sequence stops after the first element
    /// that fails to parse.
    pub fn iter(&self) -> SeqIter<'a, T> {
        match self.repr {
            Repr::Encoded { raw, count, ctx } => {
                SeqIter { state: State::Encoded { r: Reader::new(raw), left: count, ctx } }
            }
            Repr::Slice(items) => SeqIter { state: State::Slice(items.iter()) },
        }
    }

    /// Read a sequence: the list header, then each element's structure is checked
    /// (depth-bounded) and kept as bytes.
    pub(crate) fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
        let count = r.list_any()?;
        let from = r.position();
        for _ in 0..count {
            r.skip()?;
        }
        Ok(Self { repr: Repr::Encoded { raw: r.slice(from, r.position())?, count, ctx } })
    }

    pub(crate) fn read_opt(r: &mut Reader<'a>, ctx: Ctx) -> Result<Option<Self>> {
        if r.absent() { Ok(None) } else { Self::read(r, ctx).map(Some) }
    }

    /// Write the sequence: its length, then every element.
    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        w.list(self.len())?;
        match self.repr {
            // Checked element by element when it was read.
            Repr::Encoded { raw, .. } => w.raw(raw),
            Repr::Slice(items) => items.iter().try_for_each(|item| item.write(w)),
        }
    }

    pub(crate) fn write_opt(seq: Option<Self>, w: &mut Writer<'_>) -> Result<()> {
        match seq {
            Some(seq) => seq.write(w),
            None => w.absent(),
        }
    }
}

impl<'a, T: Element<'a>> IntoIterator for Seq<'a, T> {
    type Item = Result<T>;
    type IntoIter = SeqIter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T: Element<'a>> IntoIterator for &Seq<'a, T> {
    type Item = Result<T>;
    type IntoIter = SeqIter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Two sequences are equal when they yield equal elements (or equal errors), whether
/// encoded or built.
impl<'a, T: Element<'a>> PartialEq for Seq<'a, T> {
    fn eq(&self, other: &Self) -> bool {
        self.len() == other.len() && self.iter().eq(other.iter())
    }
}

impl<'a, T: Element<'a>> Eq for Seq<'a, T> {}

impl<T> fmt::Debug for Seq<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Seq").field("len", &self.len()).finish_non_exhaustive()
    }
}

/// Iterator over a [`Seq`].
pub struct SeqIter<'a, T> {
    state: State<'a, T>,
}

enum State<'a, T> {
    Encoded { r: Reader<'a>, left: usize, ctx: Ctx },
    Slice(core::slice::Iter<'a, T>),
}

impl<'a, T: Element<'a>> Iterator for SeqIter<'a, T> {
    type Item = Result<T>;

    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.state {
            State::Slice(items) => items.next().copied().map(Ok),
            State::Encoded { r, left, ctx } => {
                if *left == 0 {
                    return None;
                }
                *left -= 1;
                let item = T::read(r, *ctx);
                if item.is_err() {
                    *left = 0;
                }
                Some(item)
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match &self.state {
            State::Slice(items) => items.size_hint(),
            State::Encoded { left, .. } => (0, Some(*left)),
        }
    }
}

impl<T> fmt::Debug for SeqIter<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SeqIter").finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;
    use crate::{ListEntry, Obis, Unit};
    use std::format;

    #[test]
    fn iterators_know_how_many_are_left() {
        let entries =
            [ListEntry::number(Obis::POWER, Unit::W, 0, 1), ListEntry::number(Obis::POWER, Unit::W, 0, 2)];
        let mut built = Seq::from_slice(&entries).iter();
        assert_eq!(built.size_hint(), (2, Some(2)));
        built.next();
        assert_eq!(built.size_hint(), (1, Some(1)));
        let mut buf = [0u8; 64];
        let mut w = Writer::new(&mut buf);
        Seq::from_slice(&entries).write(&mut w).unwrap();
        let n = w.position();
        let decoded: Seq<'_, ListEntry<'_>> = Seq::read(&mut Reader::new(&buf[..n]), Ctx::default()).unwrap();
        let mut it = decoded.iter();
        assert_eq!(it.size_hint(), (0, Some(2)));
        it.next();
        assert_eq!(it.size_hint(), (0, Some(1)));
        assert_eq!(format!("{it:?}"), "SeqIter { .. }");
        assert_eq!(decoded, Seq::from_slice(&entries));
    }
}