sml-rs 0.4.0

Smart Message Language (SML) parser written in Rust
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! Smart Message Language (SML) parser written in Rust.
//!
//! Modern German power meters periodically send SML-encoded data via an optical interface.
//! The main use-case of this library is to decode that data.
//!
//! See the [`transport`] module for encoding / decoding the SML transport protocol v1 and the
//! [`parser`] module for parsing decoded data into SML data structures.
//!
//! Complete examples of how to use the library can be found on github in the [`examples`](https://github.com/felixwrt/sml-rs/tree/main/examples) folder.
//!
//! # Feature flags
//! - **`std`** (default) — Remove this feature to make the library `no_std` compatible.
//! - **`alloc`** (default) — Implementations using allocations (`alloc::Vec` et al.).
//! - **`embedded_hal`** — Allows using pins implementing `embedded_hal::serial::Read` in [`SmlReader`](SmlReader::from_eh_reader).
//! - **`nb`** - Enables non-blocking APIs using the `nb` crate.
//!
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![deny(unsafe_code)]
#![warn(missing_docs)]

use core::fmt;
use core::{borrow::Borrow, marker::PhantomData};

#[cfg(feature = "alloc")]
use parser::complete::{parse, File};
use parser::streaming::Parser;
use parser::ParseError;
use transport::{DecodeErr, DecoderReader, ReadDecodedError};
use util::{ArrayBuf, Buffer};

#[cfg(feature = "alloc")]
extern crate alloc;

pub mod parser;
pub mod transport;
pub mod util;

use util::ByteSource;

/// Error returned by functions parsing sml data read from a reader
#[derive(Debug)]
pub enum ReadParsedError<ReadErr>
where
    ReadErr: core::fmt::Debug,
{
    /// Error while parsing
    ParseErr(ParseError),
    /// Error while decoding the data (e.g. checksum mismatch)
    DecodeErr(DecodeErr),
    /// Error while reading from the internal byte source
    ///
    /// (inner_error, num_discarded_bytes)
    IoErr(ReadErr, usize),
}

impl<ReadErr> From<ReadDecodedError<ReadErr>> for ReadParsedError<ReadErr>
where
    ReadErr: core::fmt::Debug,
{
    fn from(value: ReadDecodedError<ReadErr>) -> Self {
        match value {
            ReadDecodedError::DecodeErr(x) => ReadParsedError::DecodeErr(x),
            ReadDecodedError::IoErr(x, num_discarded) => ReadParsedError::IoErr(x, num_discarded),
        }
    }
}

impl<ReadErr> From<ParseError> for ReadParsedError<ReadErr>
where
    ReadErr: core::fmt::Debug,
{
    fn from(value: ParseError) -> Self {
        ReadParsedError::ParseErr(value)
    }
}

impl<ReadErr> fmt::Display for ReadParsedError<ReadErr>
where
    ReadErr: core::fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <Self as fmt::Debug>::fmt(self, f)
    }
}

#[cfg(feature = "std")]
impl<ReadErr> std::error::Error for ReadParsedError<ReadErr> where ReadErr: core::fmt::Debug {}

// ===========================================================================
// ===========================================================================
//      `SmlReader` + impls
// ===========================================================================
// ===========================================================================

/// Main API of `sml-rs`
///
/// `SmlReader` is used to read sml data. It allows reading from various data
/// sources and can produce different output depending on the use-case.
///
/// ## Example
///
/// The following example shows how to parse an sml data set from a file:
///
/// ```
/// # #[cfg(feature = "std")] {
/// # use sml_rs::{parser::complete::File, SmlReader};
/// use std::fs;
/// let f = fs::File::open("sample.bin").unwrap();
/// let mut reader = SmlReader::from_reader(f);
/// match reader.read::<File>() {
///     Ok(x) => println!("Got result: {:#?}", x),
///     Err(e) => println!("Error: {:?}", e),
/// }
/// # }
/// ```
/// ### Data Source
///
/// The `SmlReader` struct can be used with several kinds of data providers:
///
/// | Constructor (`SmlReader::...`)          | Expected data type | Usage examples |
/// |-----------------------------------------------------|-----------|------------|
/// |[`from_reader`](SmlReader::from_reader) **¹**             | `impl std::io::Read` | files, sockets, serial ports (see `serialport-rs` crate) |
/// |[`from_eh_reader`](SmlReader::from_eh_reader) **²** | `impl embedded_hal::serial::Read<u8>` | microcontroller pins |
/// |[`from_slice`](SmlReader::from_slice)                | `&[u8]` | arrays, vectors, ... |
/// |[`from_iterator`](SmlReader::from_iterator)                  | `impl IntoIterator<Item = impl Borrow<u8>>)` | anything that can be turned into an iterator over bytes |
///
/// ***¹** requires feature `std` (on by default); **²** requires optional feature `embedded_hal`*
///
/// ### Internal Buffer
///
/// `SmlReader` reads sml messages into an internal buffer. By default, a static
/// buffer with a size of 8 KiB is used, which should be more than enough for
/// typical messages.
///
/// It is possible to use a different static buffer size or use a dynamically
/// allocated buffer that can grow as necessary. `SmlReader` provides two associated
/// functions for this purpose:
///
/// - [`SmlReader::with_static_buffer<N>()`](SmlReader::with_static_buffer)
/// - [`SmlReader::with_vec_buffer()`](SmlReader::with_vec_buffer) *(requires feature `alloc` (on by default))*
///
/// These functions return a builder object ([`SmlReaderBuilder`]) that provides methods to create an [`SmlReader`]
/// from the different data sources shown above.
///
/// **Examples**
///
/// Creating a reader with a static 1KiB buffer from a slice:
///
/// ```
/// # use sml_rs::SmlReader;
/// let data = [1, 2, 3, 4, 5];
/// let reader = SmlReader::with_static_buffer::<1024>().from_slice(&data);
/// ```
///
/// Creating a reader with a dynamically-sized buffer from an iterable:
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// # use sml_rs::SmlReader;
/// let data = [1, 2, 3, 4, 5];
/// let reader_2 = SmlReader::with_vec_buffer().from_iterator(&data);
/// # }
/// ```
///
/// ### Reading transmissions
///
/// Once a `SmlReader` is instantiated, it can be used to read, decode and parse SML messages. `SmlReader`
/// provides two functions for this, [`read<T>`](DecoderReader::read) and [`next<T>`](DecoderReader::next).
///
/// ```
/// # use sml_rs::{SmlReader, DecodedBytes};
/// let data = include_bytes!("../sample.bin");
/// let mut reader = SmlReader::from_slice(data.as_slice());
///
/// let bytes = reader.read::<DecodedBytes>();
/// assert!(matches!(bytes, Ok(bytes)));
/// let bytes = reader.read::<DecodedBytes>();
/// assert!(matches!(bytes, Err(_)));
///
/// let mut reader = SmlReader::from_slice(data.as_slice());
///
/// let bytes = reader.next::<DecodedBytes>();
/// assert!(matches!(bytes, Some(Ok(bytes))));
/// let bytes = reader.next::<DecodedBytes>();
/// assert!(matches!(bytes, None));
/// ```
///
/// ### Target Type
///
/// [`read<T>`](DecoderReader::read) and [`next<T>`](DecoderReader::next) can be used to parse sml
/// transmissions into several different representations:
///
/// - [`DecodedBytes`]: a slice of bytes containing the decoded message. No parsing is done.
/// - [`File`]: a struct containing completely parsed sml data. (requires feature `"alloc"`)
/// - [`Parser`]: an streaming parser for sml data.
///
/// **Examples**
///
/// ```
/// # use sml_rs::{SmlReader, DecodedBytes, parser::streaming::Parser};
/// # #[cfg(feature = "alloc")]
/// # use sml_rs::parser::complete::File;
/// let data = include_bytes!("../sample.bin");
/// let mut reader = SmlReader::from_slice(data.as_slice());
///
/// let bytes = reader.read::<DecodedBytes>();
/// # #[cfg(feature = "alloc")] {
/// let file = reader.read::<File>();
/// # }
/// let parser = reader.read::<Parser>();
/// ```
pub struct SmlReader<R, Buf>
where
    R: ByteSource,
    Buf: Buffer,
{
    decoder: DecoderReader<Buf, R>,
}

pub(crate) type DummySmlReader = SmlReader<util::SliceReader<'static>, ArrayBuf<0>>;

impl DummySmlReader {
    /// Returns a builder with a static internal buffer of size `N`.
    ///
    /// Use the `from_*` methods on the builder to create an `SmlReader`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sml_rs::SmlReader;
    /// let data = [1, 2, 3];
    /// let reader = SmlReader::with_static_buffer::<1024>().from_slice(&data);
    /// ```
    pub fn with_static_buffer<const N: usize>() -> SmlReaderBuilder<ArrayBuf<N>> {
        SmlReaderBuilder { buf: PhantomData }
    }

    /// Returns a builder with a dynamically-sized internal buffer.
    ///
    /// Use the `from_*` methods on the builder to create an `SmlReader`.
    ///
    /// *This function is available only if sml-rs is built with the `"alloc"` feature.*
    ///
    /// # Examples
    ///
    /// ```
    /// # use sml_rs::SmlReader;
    /// let data = [1, 2, 3];
    /// let reader = SmlReader::with_vec_buffer().from_slice(&data);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn with_vec_buffer() -> SmlReaderBuilder<alloc::vec::Vec<u8>> {
        SmlReaderBuilder { buf: PhantomData }
    }

    /// Build an `SmlReader` from a type implementing `std::io::Read`.
    ///
    /// *This function is available only if sml-rs is built with the `"std"` feature.*
    ///
    /// # Examples
    ///
    /// ```
    /// # use sml_rs::SmlReader;
    /// let data = [1, 2, 3];
    /// let cursor = std::io::Cursor::new(data);  // implements std::io::Read
    /// let reader = SmlReader::from_reader(cursor);
    /// ```
    #[cfg(feature = "std")]
    pub fn from_reader<R>(reader: R) -> SmlReader<util::IoReader<R>, DefaultBuffer>
    where
        R: std::io::Read,
    {
        SmlReader {
            decoder: DecoderReader::new(util::IoReader::new(reader)),
        }
    }

    /// Build an `SmlReader` from a type implementing `embedded_hal::serial::Read<u8>`.
    ///
    /// *This function is available only if sml-rs is built with the `"embedded-hal"` feature.*
    ///
    /// # Examples
    ///
    /// ```
    /// # use sml_rs::SmlReader;
    /// // usually provided by hardware abstraction layers (HALs) for specific chips
    /// // let pin = ...;
    /// # struct Pin;
    /// # impl embedded_hal::serial::Read<u8> for Pin {
    /// #     type Error = ();
    /// #     fn read(&mut self) -> nb::Result<u8, Self::Error> { Ok(123) }
    /// # }
    /// # let pin = Pin;
    ///
    /// let reader = SmlReader::from_eh_reader(pin);
    /// ```
    #[cfg(feature = "embedded_hal")]
    pub fn from_eh_reader<R, E>(reader: R) -> SmlReader<util::EhReader<R, E>, DefaultBuffer>
    where
        R: embedded_hal::serial::Read<u8, Error = E>,
    {
        SmlReader {
            decoder: DecoderReader::new(util::EhReader::new(reader)),
        }
    }

    /// Build an `SmlReader` from a slice of bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sml_rs::SmlReader;
    /// let data: &[u8] = &[1, 2, 3];
    /// let reader = SmlReader::from_slice(data);
    /// ```
    pub fn from_slice(reader: &[u8]) -> SmlReader<util::SliceReader<'_>, DefaultBuffer> {
        SmlReader {
            decoder: DecoderReader::new(util::SliceReader::new(reader)),
        }
    }

    /// Build an `SmlReader` from a type that can be turned into a byte iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sml_rs::SmlReader;
    /// let data: [u8; 3] = [1, 2, 3];
    /// let reader = SmlReader::from_iterator(data.clone());      // [u8; 3]
    /// let reader = SmlReader::from_iterator(&data);             // &[u8; 3]
    /// let reader = SmlReader::from_iterator(data.as_slice());   // &[u8]
    /// let reader = SmlReader::from_iterator(data.iter());       // impl Iterator<Item = &u8>
    /// let reader = SmlReader::from_iterator(data.into_iter());  // impl Iterator<Item = u8>
    /// ```
    pub fn from_iterator<B, I>(
        iter: I,
    ) -> SmlReader<util::IterReader<I::IntoIter, B>, DefaultBuffer>
    where
        I: IntoIterator<Item = B>,
        B: Borrow<u8>,
    {
        SmlReader {
            decoder: DecoderReader::new(util::IterReader::new(iter.into_iter())),
        }
    }
}

impl<R, ReadErr, Buf> SmlReader<R, Buf>
where
    R: ByteSource<ReadError = ReadErr>,
    ReadErr: core::fmt::Debug,
    Buf: Buffer,
{
    /// Reads, decodes and possibly parses sml data.
    ///
    /// ```
    /// # use sml_rs::{SmlReader, DecodedBytes};
    /// let data = include_bytes!("../sample.bin");
    /// let mut reader = SmlReader::from_slice(data.as_slice());
    ///
    /// let bytes = reader.read::<DecodedBytes>();
    /// assert!(matches!(bytes, Ok(bytes)));
    /// let bytes = reader.read::<DecodedBytes>();
    /// assert!(matches!(bytes, Err(_)));
    /// ```
    ///
    /// This method can be used to parse sml data into several representations.
    /// See the module documentation for more information.
    ///
    /// When reading from a finite data source (such as a file containing a certain
    /// number of transmissions), it's easier to use [`next`](SmlReader::next) instead,
    /// which returns `None` when an EOF is read when trying to read the next transmission.
    ///
    /// See also [`read_nb`](DecoderReader::read_nb), which provides a convenient API for
    /// non-blocking byte sources.
    pub fn read<'i, T>(&'i mut self) -> Result<T, T::Error>
    where
        T: SmlParse<'i, Result<&'i [u8], ReadDecodedError<ReadErr>>>,
    {
        T::parse_from(self.decoder.read())
    }

    /// Tries to read, decode and possibly parse sml data.
    ///
    /// ```
    /// # use sml_rs::{SmlReader, DecodedBytes};
    /// let data = include_bytes!("../sample.bin");
    /// let mut reader = SmlReader::from_slice(data.as_slice());
    ///
    /// let bytes = reader.next::<DecodedBytes>();
    /// assert!(matches!(bytes, Some(Ok(bytes))));
    /// let bytes = reader.next::<DecodedBytes>();
    /// assert!(matches!(bytes, None));
    /// ```
    ///
    /// This method can be used to parse sml data into several representations.
    /// See the module documentation for more information.
    ///
    /// When reading from a data source that will provide data infinitely (such
    /// as from a serial port), it's easier to use [`read`](SmlReader::read) instead.
    ///
    /// See also [`next_nb`](SmlReader::next_nb), which provides a convenient API for
    /// non-blocking byte sources.
    pub fn next<'i, T>(&'i mut self) -> Option<Result<T, T::Error>>
    where
        T: SmlParse<'i, Result<&'i [u8], ReadDecodedError<ReadErr>>>,
    {
        Some(T::parse_from(self.decoder.next()?))
    }

    /// Reads, decodes and possibly parses sml data (non-blocking).
    ///
    /// ```
    /// # use sml_rs::{SmlReader, DecodedBytes};
    /// let data = include_bytes!("../sample.bin");
    /// let mut reader = SmlReader::from_slice(data.as_slice());
    ///
    /// let bytes = nb::block!(reader.read_nb::<DecodedBytes>());
    /// assert!(matches!(bytes, Ok(bytes)));
    /// let bytes = nb::block!(reader.read_nb::<DecodedBytes>());
    /// assert!(matches!(bytes, Err(_)));
    /// ```
    ///
    /// Same as [`read`](SmlReader::read) except that it returns `nb::Result`.
    /// If reading from the byte source indicates that data isn't available yet,
    /// this method returns `Err(nb::Error::WouldBlock)`.
    ///
    /// Using `nb::Result` allows this method to be awaited using the `nb::block!` macro.
    ///
    /// *This function is available only if sml-rs is built with the `"nb"` or `"embedded_hal"` features.*
    #[cfg(feature = "nb")]
    pub fn read_nb<'i, T>(&'i mut self) -> nb::Result<T, T::Error>
    where
        T: SmlParse<'i, Result<&'i [u8], ReadDecodedError<ReadErr>>>,
    {
        // TODO: this could probably be written better
        let res = match self.decoder.read_nb() {
            Ok(x) => Ok(x),
            Err(nb::Error::WouldBlock) => return Err(nb::Error::WouldBlock),
            Err(nb::Error::Other(e)) => Err(e),
        };
        T::parse_from(res).map_err(nb::Error::Other)
    }

    /// Tries to read, decode and possibly parse sml data (non-blocking).
    ///
    /// ```
    /// # use sml_rs::{SmlReader, DecodedBytes};
    /// let data = include_bytes!("../sample.bin");
    /// let mut reader = SmlReader::from_slice(data.as_slice());
    ///
    /// let bytes = nb::block!(reader.next_nb::<DecodedBytes>());
    /// assert!(matches!(bytes, Ok(Some(bytes))));
    /// let bytes = nb::block!(reader.next_nb::<DecodedBytes>());
    /// assert!(matches!(bytes, Ok(None)));
    /// ```
    ///
    /// Same as [`next`](SmlReader::next) except that it returns `nb::Result`.
    /// If reading from the byte source indicates that data isn't available yet,
    /// this method returns `Err(nb::Error::WouldBlock)`.
    ///
    /// Using `nb::Result` allows this method to be awaited using the `nb::block!` macro.
    ///
    /// *This function is available only if sml-rs is built with the `"nb"` or `"embedded_hal"` features.*
    #[cfg(feature = "nb")]
    pub fn next_nb<'i, T>(&'i mut self) -> nb::Result<Option<T>, T::Error>
    where
        T: SmlParse<'i, Result<&'i [u8], ReadDecodedError<ReadErr>>>,
    {
        // TODO: this could probably be written better
        let res = match self.decoder.next_nb() {
            Ok(None) => return Ok(None),
            Ok(Some(x)) => Ok(x),
            Err(nb::Error::WouldBlock) => return Err(nb::Error::WouldBlock),
            Err(nb::Error::Other(e)) => Err(e),
        };
        T::parse_from(res).map(Some).map_err(nb::Error::Other)
    }
}

type DefaultBuffer = ArrayBuf<{ 8 * 1024 }>;

/// Builder struct for `SmlReader` that allows configuring the internal buffer type.
///
/// See [here](SmlReader#internal-buffer) for an explanation of the different internal
/// buffer types and how to use the builder to customize them.
pub struct SmlReaderBuilder<Buf: Buffer> {
    buf: PhantomData<Buf>,
}

impl<Buf: Buffer> Clone for SmlReaderBuilder<Buf> {
    fn clone(&self) -> Self {
        Self { buf: PhantomData }
    }
}

impl<Buf: Buffer> SmlReaderBuilder<Buf> {
    /// Build an `SmlReader` from a type implementing `std::io::Read`.
    ///
    /// *This function is available only if sml-rs is built with the `"std"` feature.*
    ///
    /// # Examples
    ///
    /// ```
    /// # use sml_rs::SmlReader;
    /// let data = [1, 2, 3];
    /// let cursor = std::io::Cursor::new(data);  // implements std::io::Read
    /// let reader = SmlReader::with_static_buffer::<1024>().from_reader(cursor);
    /// ```
    #[cfg(feature = "std")]
    pub fn from_reader<R: std::io::Read>(self, reader: R) -> SmlReader<util::IoReader<R>, Buf> {
        SmlReader {
            decoder: DecoderReader::new(util::IoReader::new(reader)),
        }
    }

    /// Build an `SmlReader` from a type implementing `embedded_hal::serial::Read<u8>`.
    ///
    /// *This function is available only if sml-rs is built with the `"embedded-hal"` feature.*
    ///
    /// # Examples
    ///
    /// ```
    /// # use sml_rs::SmlReader;
    /// // usually provided by hardware abstraction layers (HALs) for specific chips
    /// // let pin = ...;
    /// # struct Pin;
    /// # impl embedded_hal::serial::Read<u8> for Pin {
    /// #     type Error = ();
    /// #     fn read(&mut self) -> nb::Result<u8, Self::Error> { Ok(123) }
    /// # }
    /// # let pin = Pin;
    ///
    /// let reader = SmlReader::with_static_buffer::<1024>().from_eh_reader(pin);
    /// ```
    #[cfg(feature = "embedded_hal")]
    pub fn from_eh_reader<R: embedded_hal::serial::Read<u8, Error = E>, E>(
        self,
        reader: R,
    ) -> SmlReader<util::EhReader<R, E>, Buf> {
        SmlReader {
            decoder: DecoderReader::new(util::EhReader::new(reader)),
        }
    }

    /// Build an `SmlReader` from a slice of bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sml_rs::SmlReader;
    /// let data: &[u8] = &[1, 2, 3];
    /// let reader = SmlReader::with_static_buffer::<1024>().from_slice(data);
    /// ```
    pub fn from_slice(self, reader: &[u8]) -> SmlReader<util::SliceReader<'_>, Buf> {
        SmlReader {
            decoder: DecoderReader::new(util::SliceReader::new(reader)),
        }
    }

    /// Build an `SmlReader` from a type that can be turned into a byte iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sml_rs::SmlReader;
    /// let data: [u8; 3] = [1, 2, 3];
    /// let builder = SmlReader::with_static_buffer::<1024>();
    /// let reader = builder.clone().from_iterator(data.clone());      // [u8; 3]
    /// let reader = builder.clone().from_iterator(&data);             // &[u8; 3]
    /// let reader = builder.clone().from_iterator(data.as_slice());   // &[u8]
    /// let reader = builder.clone().from_iterator(data.iter());       // impl Iterator<Item = &u8>
    /// let reader = builder.clone().from_iterator(data.into_iter());  // impl Iterator<Item = u8>
    /// ```
    pub fn from_iterator<B, I>(self, iter: I) -> SmlReader<util::IterReader<I::IntoIter, B>, Buf>
    where
        I: IntoIterator<Item = B>,
        B: Borrow<u8>,
    {
        SmlReader {
            decoder: DecoderReader::new(util::IterReader::new(iter.into_iter())),
        }
    }
}

/// Helper trait implemented for types that can be built from decoded bytes.
pub trait SmlParse<'i, T>: Sized + util::private::Sealed {
    /// The error produced if parsing fails or the input contained an error.
    type Error;

    /// Takes the result of decoding and parses it into the resulting type.
    fn parse_from(value: T) -> Result<Self, Self::Error>;
}

/// Type alias for decoded bytes.
pub type DecodedBytes<'i> = &'i [u8];

type ReadDecodedRes<'i, ReadErr> = Result<&'i [u8], ReadDecodedError<ReadErr>>;

impl<'i, ReadErr> SmlParse<'i, ReadDecodedRes<'i, ReadErr>> for DecodedBytes<'i>
where
    ReadErr: core::fmt::Debug,
{
    type Error = ReadDecodedError<ReadErr>;

    fn parse_from(value: ReadDecodedRes<'i, ReadErr>) -> Result<Self, Self::Error> {
        value
    }
}

impl<'i> SmlParse<'i, &'i [u8]> for DecodedBytes<'i> {
    type Error = core::convert::Infallible;

    fn parse_from(value: &'i [u8]) -> Result<Self, Self::Error> {
        Ok(value)
    }
}

impl<'i> util::private::Sealed for DecodedBytes<'i> {}

#[cfg(feature = "alloc")]
impl<'i, ReadErr> SmlParse<'i, ReadDecodedRes<'i, ReadErr>> for File<'i>
where
    ReadErr: core::fmt::Debug,
{
    type Error = ReadParsedError<ReadErr>;

    fn parse_from(value: ReadDecodedRes<'i, ReadErr>) -> Result<Self, Self::Error> {
        Ok(parse(value?)?)
    }
}

#[cfg(feature = "alloc")]
impl<'i> SmlParse<'i, &'i [u8]> for File<'i> {
    type Error = ParseError;

    fn parse_from(value: &'i [u8]) -> Result<Self, Self::Error> {
        parse(value)
    }
}

#[cfg(feature = "alloc")]
impl<'i> util::private::Sealed for File<'i> {}

impl<'i, ReadErr> SmlParse<'i, ReadDecodedRes<'i, ReadErr>> for Parser<'i>
where
    ReadErr: core::fmt::Debug,
{
    type Error = ReadDecodedError<ReadErr>;

    fn parse_from(value: ReadDecodedRes<'i, ReadErr>) -> Result<Self, Self::Error> {
        Ok(Parser::new(value?))
    }
}

impl<'i> SmlParse<'i, &'i [u8]> for Parser<'i> {
    type Error = core::convert::Infallible;

    fn parse_from(value: &'i [u8]) -> Result<Self, Self::Error> {
        Ok(Parser::new(value))
    }
}

impl<'i> util::private::Sealed for Parser<'i> {}

#[test]
fn test_smlreader_construction() {
    let arr = [1, 2, 3, 4, 5];

    // no deps

    // using default buffer
    SmlReader::from_slice(&arr);
    SmlReader::from_iterator(&arr);
    SmlReader::from_iterator(arr.iter().map(|x| x + 1));
    #[cfg(feature = "std")]
    SmlReader::from_reader(std::io::Cursor::new(&arr));

    // using static buffer
    SmlReader::with_static_buffer::<1234>().from_slice(&arr);
    SmlReader::with_static_buffer::<1234>().from_iterator(arr.iter().map(|x| x + 1));
    #[cfg(feature = "std")]
    SmlReader::with_static_buffer::<1234>().from_reader(std::io::Cursor::new(&arr));

    // using dynamic buffer
    #[cfg(feature = "alloc")]
    SmlReader::with_vec_buffer().from_slice(&arr);
    #[cfg(feature = "alloc")]
    SmlReader::with_vec_buffer().from_iterator(arr.iter().map(|x| x + 1));
    #[cfg(feature = "std")]
    SmlReader::with_vec_buffer().from_reader(std::io::Cursor::new(&arr));
}

#[test]
#[cfg(feature = "embedded_hal")]
fn test_smlreader_eh_construction() {
    // dummy struct implementing `Read`
    struct Pin;
    impl embedded_hal::serial::Read<u8> for Pin {
        type Error = i16;

        fn read(&mut self) -> nb::Result<u8, Self::Error> {
            Ok(123)
        }
    }

    // using default buffer
    SmlReader::from_eh_reader(Pin);

    // using static buffer
    SmlReader::with_static_buffer::<1234>().from_eh_reader(Pin);

    // using dynamic buffer
    #[cfg(feature = "alloc")]
    SmlReader::with_vec_buffer().from_eh_reader(Pin);
}

mod read_tests {
    #[test]
    fn test_smlreader_reading() {
        // check that different types can be used with read and next
        #[cfg(feature = "alloc")]
        use super::File;
        use super::{DecodedBytes, Parser, SmlReader};

        let bytes = [1, 2, 3, 4];
        let mut reader = SmlReader::from_slice(&bytes);

        let _ = reader.read::<DecodedBytes>();
        let _: Result<DecodedBytes, _> = reader.read();

        #[cfg(feature = "alloc")]
        let _ = reader.read::<File>();
        let _ = reader.read::<Parser>();

        let _ = reader.next::<DecodedBytes>();
        #[cfg(feature = "alloc")]
        let _ = reader.next::<File>();
        let _ = reader.next::<Parser>();
    }

    #[test]
    #[cfg(feature = "nb")]
    fn test_smlreader_reading_nb() {
        // check that different types can be used with read_nb and next_nb
        #[cfg(feature = "alloc")]
        use super::File;
        use super::{DecodedBytes, Parser, SmlReader};

        let bytes = [1, 2, 3, 4];
        let mut reader = SmlReader::from_slice(&bytes);

        let _ = reader.next_nb::<DecodedBytes>();
        #[cfg(feature = "alloc")]
        let _ = reader.next_nb::<File>();
        let _ = reader.next_nb::<Parser>();

        let _ = reader.read_nb::<DecodedBytes>();
        #[cfg(feature = "alloc")]
        let _ = reader.read_nb::<File>();
        let _ = reader.read_nb::<Parser>();
    }
}