rusmpp/ende/
encode.rs

1use crate::tri;
2
3use super::length::Length;
4
5#[derive(Debug)]
6pub enum EncodeError {
7    IoError(std::io::Error),
8}
9
10impl From<std::io::Error> for EncodeError {
11    fn from(e: std::io::Error) -> Self {
12        EncodeError::IoError(e)
13    }
14}
15
16impl std::fmt::Display for EncodeError {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        match self {
19            EncodeError::IoError(e) => write!(f, "I/O error: {}", e),
20        }
21    }
22}
23
24impl std::error::Error for EncodeError {
25    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
26        match self {
27            EncodeError::IoError(e) => Some(e),
28        }
29    }
30
31    fn cause(&self) -> Option<&dyn std::error::Error> {
32        self.source()
33    }
34}
35
36pub trait Encode: Length {
37    /// Encode a value to a writer
38    fn encode_to<W: std::io::Write>(&self, writer: &mut W) -> Result<(), EncodeError>;
39
40    /// Encode a value into a vector
41    fn encode_into_vec(&self) -> Result<Vec<u8>, EncodeError> {
42        let mut buf = Vec::with_capacity(self.length());
43
44        tri!(self.encode_to(&mut buf));
45
46        Ok(buf)
47    }
48}