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
use core::fmt::{Display, Formatter};
#[cfg(feature = "std")]
use std::error::Error;

#[derive(Debug)]
pub enum ParserError {
    InvalidFlag { flag_type: &'static str, value: u32 },
    InvalidEnum { enum_type: &'static str, value: u32 },
    UnknownMessage { id: u32 },
}

impl Display for ParserError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InvalidFlag { flag_type, value } => write!(
                f,
                "Invalid flag value for flag type {flag_type:?}, got {value:?}"
            ),
            Self::InvalidEnum { enum_type, value } => write!(
                f,
                "Invalid enum value for enum type {enum_type:?}, got {value:?}"
            ),
            Self::UnknownMessage { id } => write!(f, "Unknown message with ID {id:?}"),
        }
    }
}

#[cfg(feature = "std")]
impl Error for ParserError {}

#[derive(Debug)]
pub enum MessageReadError {
    #[cfg(feature = "std")]
    Io(std::io::Error),
    #[cfg(any(feature = "embedded", feature = "embedded-hal-02"))]
    Io,
    Parse(ParserError),
}

impl Display for MessageReadError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            #[cfg(feature = "std")]
            Self::Io(e) => write!(f, "Failed to read message: {e:#?}"),
            #[cfg(any(feature = "embedded", feature = "embedded-hal-02"))]
            Self::Io => write!(f, "Failed to read message"),
            Self::Parse(e) => write!(f, "Failed to read message: {e:#?}"),
        }
    }
}

#[cfg(feature = "std")]
impl Error for MessageReadError {}

#[cfg(feature = "std")]
impl From<std::io::Error> for MessageReadError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

impl From<ParserError> for MessageReadError {
    fn from(e: ParserError) -> Self {
        Self::Parse(e)
    }
}

#[derive(Debug)]
pub enum MessageWriteError {
    #[cfg(feature = "std")]
    Io(std::io::Error),
    #[cfg(any(feature = "embedded", feature = "embedded-hal-02"))]
    Io,
}

impl Display for MessageWriteError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            #[cfg(feature = "std")]
            Self::Io(e) => write!(f, "Failed to write message: {e:#?}"),
            #[cfg(any(feature = "embedded", feature = "embedded-hal-02"))]
            Self::Io => write!(f, "Failed to write message"),
        }
    }
}

#[cfg(feature = "std")]
impl Error for MessageWriteError {}

#[cfg(feature = "std")]
impl From<std::io::Error> for MessageWriteError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}