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
96
97
98
99
use crate::error::{UnexpectedBufferEndError, WrongChecksumError};

use core::fmt::{Debug, Display, Formatter};

#[cfg(all(feature = "error_trait", not(feature = "std")))]
use core::error;

#[cfg(feature = "std")]
use std::error;

#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum ParseUdpError {
    UnexpectedBufferEnd(UnexpectedBufferEndError),
    WrongChecksum(WrongChecksumError),
    LengthHeaderTooSmall {
        length_header: usize,
    },
    LengthHeaderTooLarge {
        data_length: usize,
        length_header: usize,
    },
}

impl From<UnexpectedBufferEndError> for ParseUdpError {
    #[inline]
    fn from(value: UnexpectedBufferEndError) -> Self {
        Self::UnexpectedBufferEnd(value)
    }
}

impl From<WrongChecksumError> for ParseUdpError {
    #[inline]
    fn from(value: WrongChecksumError) -> Self {
        Self::WrongChecksum(value)
    }
}

impl Display for ParseUdpError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::UnexpectedBufferEnd(err) => {
                write!(f, "{err}")
            }
            Self::WrongChecksum(err) => {
                write!(f, "{err}")
            }
            Self::LengthHeaderTooSmall { length_header } => {
                write!(
                    f,
                    "Length header is {length_header} but was expected to be at least 8"
                )
            }
            Self::LengthHeaderTooLarge {
                data_length,
                length_header,
            } => {
                write!(
                    f,
                    "Length header expected to be at most {data_length} but was {length_header}"
                )
            }
        }
    }
}

#[cfg(feature = "error_trait")]
impl error::Error for ParseUdpError {}

#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum SetLengthError {
    UnexpectedBufferEnd(UnexpectedBufferEndError),
    LengthTooSmall { length: usize },
}

impl From<UnexpectedBufferEndError> for SetLengthError {
    #[inline]
    fn from(value: UnexpectedBufferEndError) -> Self {
        Self::UnexpectedBufferEnd(value)
    }
}

impl Display for SetLengthError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::UnexpectedBufferEnd(err) => {
                write!(f, "{err}")
            }
            Self::LengthTooSmall { length } => {
                write!(
                    f,
                    "Provided length header is {length} but has to be at least 8"
                )
            }
        }
    }
}

#[cfg(feature = "error_trait")]
impl error::Error for SetLengthError {}