dsf_core/base/
mod.rs

1//! Base module provides a low-level structure for data encoding and decoding
2
3use core::marker::PhantomData;
4
5pub mod header;
6pub use header::*;
7
8pub mod body;
9pub use body::*;
10
11/// Parse trait for building parse-able objects
12pub trait Parse {
13    /// Output type returned from parsing
14    type Output;
15    /// Error type returned on parse error
16    type Error;
17    /// Parse method consumes a slice and returns an object and the remaining slice.
18    fn parse(buff: &[u8]) -> Result<(Self::Output, usize), Self::Error>;
19
20    /// Parse iter consumes a slice and returns an iterator over decoded objects
21    fn parse_iter<'a>(buff: &'a [u8]) -> ParseIter<'a, Self::Output, Self::Error> {
22        ParseIter {
23            buff,
24            index: 0,
25            _t: PhantomData,
26            _e: PhantomData,
27        }
28    }
29}
30
31/// Iterative parser object, constructed with `Parse::parse_iter` for types implementing `Parse`
32pub struct ParseIter<'a, T, E> {
33    buff: &'a [u8],
34    index: usize,
35    _t: PhantomData<T>,
36    _e: PhantomData<E>,
37}
38
39impl<'a, T, E> Iterator for ParseIter<'a, T, E>
40where
41    T: Parse<Output = T, Error = E>,
42{
43    type Item = Result<T, E>;
44
45    fn next(&mut self) -> Option<Self::Item> {
46        if self.index == self.buff.len() {
47            return None;
48        }
49
50        let (v, n) = match T::parse(&self.buff[self.index..]) {
51            Ok((v, n)) => (v, n),
52            Err(e) => return Some(Err(e)),
53        };
54
55        self.index += n;
56
57        Some(Ok(v))
58    }
59}
60
61/// Encode trait for building encodable objects
62pub trait Encode {
63    /// Error type returned on parse error
64    type Error;
65
66    /// Encode method writes object data to the provided writer
67    fn encode(&self, buff: &mut [u8]) -> Result<usize, Self::Error>;
68
69    /// Encode a iterator of encodable objects
70    fn encode_iter<'a, V: Iterator<Item = &'a Self>>(
71        vals: V,
72        buff: &mut [u8],
73    ) -> Result<usize, Self::Error>
74    where
75        Self: 'static,
76    {
77        let mut index = 0;
78
79        for i in vals {
80            index += i.encode(&mut buff[index..])?;
81        }
82
83        Ok(index)
84    }
85}