Skip to main content

enc/data/
encoder.rs

1use crate::{Error, data};
2
3/// Responsible for encoding binary data.
4pub trait Encoder {
5    /// Gets the length of the encoded `data`.
6    fn encoded_len(&self, data: &[u8]) -> Result<usize, Error>;
7
8    /// Encodes the `data` into the `target` slice.
9    ///
10    /// Returns the length of the encoded `data`.
11    fn encode_to_slice(&self, data: &[u8], target: &mut [u8]) -> Result<usize, Error>;
12
13    /// Appends the encoded `data` to the `target` vec.
14    ///
15    /// Returns the length of the encoded `data`.
16    fn append_to_vec(&self, data: &[u8], target: &mut Vec<u8>) -> Result<usize, Error> {
17        data::util::default_append_to_vec(
18            data,
19            target,
20            |d| self.encoded_len(d),
21            |d, t| self.encode_to_slice(d, t),
22        )
23    }
24
25    /// Encodes the `data` as a vec.
26    ///
27    /// Returns the vec.
28    fn encode_as_vec(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
29        let mut vec: Vec<u8> = Vec::default();
30        self.append_to_vec(data, &mut vec)?;
31        Ok(vec)
32    }
33}