Skip to main content

sml_kit/
seq.rs

1//! `SEQUENCE OF …` without allocation: a list that is either encoded bytes from a frame,
2//! parsed one element at a time, or a borrowed slice built for writing.
3
4use core::fmt;
5
6use crate::Result;
7use crate::message::ParseOptions;
8use crate::tl::{Reader, Writer};
9
10/// How the elements of an encoded sequence are read: the options of the message they
11/// came in, and whether the DZG power correction applies to this list.
12#[doc(hidden)]
13#[derive(Clone, Copy, Debug, Default)]
14pub struct Ctx {
15    pub(crate) options: ParseOptions,
16    pub(crate) dzg: bool,
17}
18
19impl Ctx {
20    pub(crate) const fn new(options: ParseOptions) -> Self {
21        Self { options, dzg: false }
22    }
23}
24
25pub(crate) mod sealed {
26    pub trait Sealed {}
27}
28
29/// An element of a [`Seq`]: [`ListEntry`](crate::ListEntry),
30/// [`PeriodEntry`](crate::PeriodEntry), [`Tree`](crate::Tree) or a name (`&[u8]`).
31/// Sealed: the encoding of each is fixed by the specification.
32pub trait Element<'a>: Sized + Copy + PartialEq + sealed::Sealed {
33    #[doc(hidden)]
34    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self>;
35    #[doc(hidden)]
36    fn write(&self, w: &mut Writer<'_>) -> Result<()>;
37}
38
39impl sealed::Sealed for &[u8] {}
40impl sealed::Sealed for crate::ListEntry<'_> {}
41impl sealed::Sealed for crate::PeriodEntry<'_> {}
42impl sealed::Sealed for crate::Tree<'_> {}
43
44/// A name: an octet string, as in a tree path or a profile's object list.
45impl<'a> Element<'a> for &'a [u8] {
46    fn read(r: &mut Reader<'a>, _: Ctx) -> Result<Self> {
47        r.octet_string()
48    }
49
50    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
51        w.octet_string(self)
52    }
53}
54
55/// An SML `SEQUENCE OF T`, parsed lazily.
56///
57/// A sequence read from a frame keeps its encoded bytes and parses each element when
58/// iterated; one built for writing borrows a slice. Both behave the same, and a built
59/// sequence equals the decoded one:
60///
61/// ```
62/// use sml_kit::{ListEntries, ListEntry, Obis, Unit};
63///
64/// let entries = [ListEntry::number(Obis::POWER, Unit::W, 0, 1337)];
65/// let list = ListEntries::from_slice(&entries);
66/// assert_eq!(list.len(), 1);
67/// assert_eq!(list.iter().next(), Some(Ok(entries[0])));
68/// ```
69///
70/// `Debug` shows only the length: the bytes of a request may hold credentials.
71pub struct Seq<'a, T> {
72    repr: Repr<'a, T>,
73}
74
75enum Repr<'a, T> {
76    Encoded { raw: &'a [u8], count: usize, ctx: Ctx },
77    Slice(&'a [T]),
78}
79
80impl<T> Clone for Repr<'_, T> {
81    fn clone(&self) -> Self {
82        *self
83    }
84}
85
86impl<T> Copy for Repr<'_, T> {}
87
88impl<T> Clone for Seq<'_, T> {
89    fn clone(&self) -> Self {
90        *self
91    }
92}
93
94impl<T> Copy for Seq<'_, T> {}
95
96impl<'a, T> Seq<'a, T> {
97    /// A sequence of `items`, for writing.
98    pub const fn from_slice(items: &'a [T]) -> Self {
99        Self { repr: Repr::Slice(items) }
100    }
101
102    /// How many elements the sequence has (for an encoded one: declares).
103    pub const fn len(&self) -> usize {
104        match self.repr {
105            Repr::Encoded { count, .. } => count,
106            Repr::Slice(items) => items.len(),
107        }
108    }
109
110    /// Whether the sequence is empty.
111    pub const fn is_empty(&self) -> bool {
112        self.len() == 0
113    }
114}
115
116impl<'a, T: Element<'a>> Seq<'a, T> {
117    /// The elements, one at a time. An encoded sequence stops after the first element
118    /// that fails to parse.
119    pub fn iter(&self) -> SeqIter<'a, T> {
120        match self.repr {
121            Repr::Encoded { raw, count, ctx } => {
122                SeqIter { state: State::Encoded { r: Reader::new(raw), left: count, ctx } }
123            }
124            Repr::Slice(items) => SeqIter { state: State::Slice(items.iter()) },
125        }
126    }
127
128    /// Read a sequence: the list header, then each element's structure is checked
129    /// (depth-bounded) and kept as bytes.
130    pub(crate) fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
131        let count = r.list_any()?;
132        let from = r.position();
133        for _ in 0..count {
134            r.skip()?;
135        }
136        Ok(Self { repr: Repr::Encoded { raw: r.slice(from, r.position())?, count, ctx } })
137    }
138
139    pub(crate) fn read_opt(r: &mut Reader<'a>, ctx: Ctx) -> Result<Option<Self>> {
140        if r.absent() { Ok(None) } else { Self::read(r, ctx).map(Some) }
141    }
142
143    /// Write the sequence: its length, then every element.
144    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
145        w.list(self.len())?;
146        match self.repr {
147            // Checked element by element when it was read.
148            Repr::Encoded { raw, .. } => w.raw(raw),
149            Repr::Slice(items) => items.iter().try_for_each(|item| item.write(w)),
150        }
151    }
152
153    pub(crate) fn write_opt(seq: Option<Self>, w: &mut Writer<'_>) -> Result<()> {
154        match seq {
155            Some(seq) => seq.write(w),
156            None => w.absent(),
157        }
158    }
159}
160
161impl<'a, T: Element<'a>> IntoIterator for Seq<'a, T> {
162    type Item = Result<T>;
163    type IntoIter = SeqIter<'a, T>;
164
165    fn into_iter(self) -> Self::IntoIter {
166        self.iter()
167    }
168}
169
170impl<'a, T: Element<'a>> IntoIterator for &Seq<'a, T> {
171    type Item = Result<T>;
172    type IntoIter = SeqIter<'a, T>;
173
174    fn into_iter(self) -> Self::IntoIter {
175        self.iter()
176    }
177}
178
179/// Two sequences are equal when they yield equal elements (or equal errors), whether
180/// encoded or built.
181impl<'a, T: Element<'a>> PartialEq for Seq<'a, T> {
182    fn eq(&self, other: &Self) -> bool {
183        self.len() == other.len() && self.iter().eq(other.iter())
184    }
185}
186
187impl<'a, T: Element<'a>> Eq for Seq<'a, T> {}
188
189impl<T> fmt::Debug for Seq<'_, T> {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        f.debug_struct("Seq").field("len", &self.len()).finish_non_exhaustive()
192    }
193}
194
195/// Iterator over a [`Seq`].
196pub struct SeqIter<'a, T> {
197    state: State<'a, T>,
198}
199
200enum State<'a, T> {
201    Encoded { r: Reader<'a>, left: usize, ctx: Ctx },
202    Slice(core::slice::Iter<'a, T>),
203}
204
205impl<'a, T: Element<'a>> Iterator for SeqIter<'a, T> {
206    type Item = Result<T>;
207
208    fn next(&mut self) -> Option<Self::Item> {
209        match &mut self.state {
210            State::Slice(items) => items.next().copied().map(Ok),
211            State::Encoded { r, left, ctx } => {
212                if *left == 0 {
213                    return None;
214                }
215                *left -= 1;
216                let item = T::read(r, *ctx);
217                if item.is_err() {
218                    *left = 0;
219                }
220                Some(item)
221            }
222        }
223    }
224
225    fn size_hint(&self) -> (usize, Option<usize>) {
226        match &self.state {
227            State::Slice(items) => items.size_hint(),
228            State::Encoded { left, .. } => (0, Some(*left)),
229        }
230    }
231}
232
233impl<T> fmt::Debug for SeqIter<'_, T> {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        f.debug_struct("SeqIter").finish_non_exhaustive()
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    extern crate std;
242    use super::*;
243    use crate::{ListEntry, Obis, Unit};
244    use std::format;
245
246    #[test]
247    fn iterators_know_how_many_are_left() {
248        let entries =
249            [ListEntry::number(Obis::POWER, Unit::W, 0, 1), ListEntry::number(Obis::POWER, Unit::W, 0, 2)];
250        let mut built = Seq::from_slice(&entries).iter();
251        assert_eq!(built.size_hint(), (2, Some(2)));
252        built.next();
253        assert_eq!(built.size_hint(), (1, Some(1)));
254        let mut buf = [0u8; 64];
255        let mut w = Writer::new(&mut buf);
256        Seq::from_slice(&entries).write(&mut w).unwrap();
257        let n = w.position();
258        let decoded: Seq<'_, ListEntry<'_>> = Seq::read(&mut Reader::new(&buf[..n]), Ctx::default()).unwrap();
259        let mut it = decoded.iter();
260        assert_eq!(it.size_hint(), (0, Some(2)));
261        it.next();
262        assert_eq!(it.size_hint(), (0, Some(1)));
263        assert_eq!(format!("{it:?}"), "SeqIter { .. }");
264        assert_eq!(decoded, Seq::from_slice(&entries));
265    }
266}