umsh_node/
app_error.rs

1use core::fmt;
2
3use umsh_core::{EncodeError as CoreEncodeError, PacketType, ParseError as CoreParseError};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub enum AppParseError {
7    Core(CoreParseError),
8    InvalidUtf8,
9    InvalidPayloadType(u8),
10    PayloadTypeNotAllowed {
11        payload_type: u8,
12        packet_type: PacketType,
13    },
14    InvalidRole(u8),
15    InvalidCommandId(u8),
16    InvalidOptionValue,
17    InvalidLength {
18        expected: usize,
19        actual: usize,
20    },
21}
22
23impl From<CoreParseError> for AppParseError {
24    fn from(value: CoreParseError) -> Self {
25        Self::Core(value)
26    }
27}
28
29impl fmt::Display for AppParseError {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        write!(f, "{self:?}")
32    }
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum AppEncodeError {
37    Core(CoreEncodeError),
38    BufferTooSmall,
39    InvalidField,
40}
41
42impl From<CoreEncodeError> for AppEncodeError {
43    fn from(value: CoreEncodeError) -> Self {
44        Self::Core(value)
45    }
46}
47
48impl fmt::Display for AppEncodeError {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        write!(f, "{self:?}")
51    }
52}
53
54#[cfg(feature = "std")]
55impl std::error::Error for AppParseError {}
56
57#[cfg(feature = "std")]
58impl std::error::Error for AppEncodeError {}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63    use umsh_core::{EncodeError, ParseError};
64
65    #[test]
66    fn app_parse_error_from_core() {
67        let e = AppParseError::from(ParseError::Truncated);
68        assert_eq!(e, AppParseError::Core(ParseError::Truncated));
69    }
70
71    #[test]
72    fn app_encode_error_from_core() {
73        let e = AppEncodeError::from(EncodeError::BufferTooSmall);
74        assert_eq!(e, AppEncodeError::Core(EncodeError::BufferTooSmall));
75    }
76
77    #[test]
78    fn display_delegates_to_debug() {
79        let e = AppParseError::InvalidUtf8;
80        assert_eq!(alloc::format!("{e}"), alloc::format!("{e:?}"));
81
82        let e = AppEncodeError::BufferTooSmall;
83        assert_eq!(alloc::format!("{e}"), alloc::format!("{e:?}"));
84    }
85}