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
// SPDX-License-Identifier: MIT

use anyhow::anyhow;
use thiserror::Error;

#[derive(Debug, Error)]
#[error("Encode error occurred: {inner}")]
pub struct EncodeError {
    inner: anyhow::Error,
}

impl From<&'static str> for EncodeError {
    fn from(msg: &'static str) -> Self {
        EncodeError {
            inner: anyhow!(msg),
        }
    }
}

impl From<String> for EncodeError {
    fn from(msg: String) -> Self {
        EncodeError {
            inner: anyhow!(msg),
        }
    }
}

impl From<anyhow::Error> for EncodeError {
    fn from(inner: anyhow::Error) -> EncodeError {
        EncodeError { inner }
    }
}

#[derive(Debug, Error)]
pub enum DecodeError {
    #[error("Invalid MAC address")]
    InvalidMACAddress,

    #[error("Invalid IP address")]
    InvalidIPAddress,

    #[error("Invalid string")]
    Utf8Error(#[from] std::string::FromUtf8Error),

    #[error("Invalid u8")]
    InvalidU8,

    #[error("Invalid u16")]
    InvalidU16,

    #[error("Invalid u32")]
    InvalidU32,

    #[error("Invalid u64")]
    InvalidU64,

    #[error("Invalid u128")]
    InvalidU128,

    #[error("Invalid i32")]
    InvalidI32,

    #[error("Invalid {name}: length {len} < {buffer_len}")]
    InvalidBufferLength {
        name: &'static str,
        len: usize,
        buffer_len: usize,
    },

    #[error(transparent)]
    Nla(#[from] crate::nla::NlaError),

    #[error(transparent)]
    Other(#[from] anyhow::Error),

    #[error("Failed to parse NLMSG_ERROR: {0}")]
    FailedToParseNlMsgError(Box<DecodeError>),

    #[error("Failed to parse NLMSG_DONE: {0}")]
    FailedToParseNlMsgDone(Box<DecodeError>),

    #[error("Failed to parse message with type {message_type}: {source}")]
    FailedToParseMessageWithType { message_type: u16, source: Box<DecodeError> },

    #[error("Failed to parse netlink header: {0}")]
    FailedToParseNetlinkHeader(Box<DecodeError>),
}

impl From<&'static str> for DecodeError {
    fn from(msg: &'static str) -> Self {
        DecodeError::Other(anyhow!(msg))
    }
}

impl From<String> for DecodeError {
    fn from(msg: String) -> Self {
        DecodeError::Other(anyhow!(msg))
    }
}