bitfold_core/
error.rs

1//! Error types shared across the stack.
2
3use std::{
4    error::Error,
5    fmt::{self, Display, Formatter},
6    io, result,
7};
8
9/// Wrapped result type for errors.
10pub type Result<T> = result::Result<T, ErrorKind>;
11
12#[derive(Debug)]
13/// Enum with all possible errors that could occur while processing packets.
14pub enum ErrorKind {
15    /// Error in decoding the packet
16    DecodingError(DecodingErrorKind),
17    /// Error relating to receiving or parsing a fragment
18    FragmentError(FragmentErrorKind),
19    /// Error relating to receiving or parsing a packet
20    PacketError(PacketErrorKind),
21    /// Wrapper around a std io::Error
22    IOError(io::Error),
23    /// Did not receive enough data
24    ReceivedDataToShort,
25    /// Protocol versions did not match
26    ProtocolVersionMismatch,
27    /// Expected header but could not be read from buffer.
28    CouldNotReadHeader(String),
29}
30
31impl Display for ErrorKind {
32    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
33        match self {
34            ErrorKind::DecodingError(e) => {
35                write!(fmt, "Something went wrong with parsing the header. Reason: {:?}.", e)
36            }
37            ErrorKind::FragmentError(e) => write!(
38                fmt,
39                "Something went wrong with receiving/parsing fragments. Reason: {:?}.",
40                e
41            ),
42            ErrorKind::PacketError(e) => {
43                write!(fmt, "Something went wrong with receiving/parsing packets. Reason: {:?}.", e)
44            }
45            ErrorKind::IOError(e) => write!(fmt, "An IO Error occurred. Reason: {:?}.", e),
46            ErrorKind::ReceivedDataToShort => {
47                write!(fmt, "The received data did not have any length.")
48            }
49            ErrorKind::ProtocolVersionMismatch => {
50                write!(fmt, "The protocol versions do not match.")
51            }
52            ErrorKind::CouldNotReadHeader(header) => {
53                write!(fmt, "Expected {} header but could not be read from buffer.", header)
54            }
55        }
56    }
57}
58
59impl Error for ErrorKind {}
60
61/// Errors that could occur while parsing packet contents
62#[derive(Debug, PartialEq, Eq, Clone)]
63pub enum DecodingErrorKind {
64    /// The PacketType could not be read
65    PacketType,
66    /// The OrderingGuarantee could not be read
67    OrderingGuarantee,
68    /// The DeliveryGuarantee could not be read
69    DeliveryGuarantee,
70}
71
72impl Display for DecodingErrorKind {
73    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
74        match *self {
75            DecodingErrorKind::PacketType => write!(fmt, "The packet type could not be read."),
76            DecodingErrorKind::OrderingGuarantee => {
77                write!(fmt, "The ordering guarantee could not be read.")
78            }
79            DecodingErrorKind::DeliveryGuarantee => {
80                write!(fmt, "The delivery guarantee could not be read.")
81            }
82        }
83    }
84}
85
86/// Errors that could occur while parsing packet contents
87#[derive(Debug, PartialEq, Eq, Clone)]
88pub enum PacketErrorKind {
89    /// The maximal allowed size of the packet was exceeded
90    ExceededMaxPacketSize,
91    /// Only `PacketType::Packet` can be fragmented
92    PacketCannotBeFragmented,
93    /// MTU is too small to accommodate packet headers and minimum payload
94    MtuTooSmall,
95    /// Packet payload too large to fragment with current MTU settings
96    PayloadTooLargeToFragment,
97}
98
99impl Display for PacketErrorKind {
100    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
101        match *self {
102            PacketErrorKind::ExceededMaxPacketSize => {
103                write!(fmt, "The packet size was bigger than the max allowed size.")
104            }
105            PacketErrorKind::PacketCannotBeFragmented => {
106                write!(fmt, "The packet type cannot be fragmented.")
107            }
108            PacketErrorKind::MtuTooSmall => {
109                write!(fmt, "MTU is too small to accommodate packet headers and minimum payload.")
110            }
111            PacketErrorKind::PayloadTooLargeToFragment => {
112                write!(fmt, "Payload too large to fragment with current MTU settings.")
113            }
114        }
115    }
116}
117
118/// Errors that could occur with constructing/parsing fragment contents
119#[derive(Debug, PartialEq, Eq, Clone)]
120pub enum FragmentErrorKind {
121    /// PacketHeader was not found in the packet
122    PacketHeaderNotFound,
123    /// Max number of allowed fragments has been exceeded
124    ExceededMaxFragments,
125    /// This fragment was already processed
126    AlreadyProcessedFragment,
127    /// Attempted to fragment with an incorrect number of fragments
128    FragmentWithUnevenNumberOfFragments,
129    /// Fragment we expected to be able to find we couldn't
130    CouldNotFindFragmentById,
131    /// Multiple ack headers sent with these fragments
132    MultipleAckHeaders,
133    /// Ack header is missing from a finished set of fragments
134    MissingAckHeader,
135}
136
137impl Display for FragmentErrorKind {
138    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
139        match *self {
140            FragmentErrorKind::PacketHeaderNotFound => {
141                write!(fmt, "Packet header was attached to fragment.")
142            }
143            FragmentErrorKind::ExceededMaxFragments => write!(
144                fmt,
145                "The total numbers of fragments are bigger than the allowed fragments."
146            ),
147            FragmentErrorKind::AlreadyProcessedFragment => {
148                write!(fmt, "The fragment received was already processed.")
149            }
150            FragmentErrorKind::FragmentWithUnevenNumberOfFragments => write!(
151                fmt,
152                "The fragment header does not contain the right fragment count."
153            ),
154            FragmentErrorKind::CouldNotFindFragmentById => write!(
155                fmt,
156                "The fragment supposed to be in a the cache but it was not found."
157            ),
158            FragmentErrorKind::MultipleAckHeaders => write!(
159                fmt,
160                "The fragment contains an ack header but a previous ack header has already been registered."
161            ),
162            FragmentErrorKind::MissingAckHeader => write!(
163                fmt,
164                "No ack headers were registered with any of the fragments."
165            ),
166        }
167    }
168}
169impl From<io::Error> for ErrorKind {
170    fn from(inner: io::Error) -> ErrorKind {
171        ErrorKind::IOError(inner)
172    }
173}
174
175impl From<PacketErrorKind> for ErrorKind {
176    fn from(inner: PacketErrorKind) -> Self {
177        ErrorKind::PacketError(inner)
178    }
179}
180
181impl From<FragmentErrorKind> for ErrorKind {
182    fn from(inner: FragmentErrorKind) -> Self {
183        ErrorKind::FragmentError(inner)
184    }
185}