miltr_common/
error.rs

1use std::io;
2
3use bytes::BytesMut;
4use thiserror::Error;
5
6use super::optneg::CompatibilityError;
7
8/// Encapsulating error for the different de-/encoding problems
9#[derive(Debug, Error)]
10pub enum ProtocolError {
11    /// Data that could not be interpreted
12    #[error(transparent)]
13    InvalidData(#[from] InvalidData),
14    /// Clearly not enough data was present
15    #[error(transparent)]
16    NotEnoughData(#[from] NotEnoughData),
17    /// If we have a protocol compatibility issue
18    #[error(transparent)]
19    CompatibilityError(#[from] CompatibilityError),
20    /// To much data was received to make sense
21    #[error("Received a packet too large to decode (len {0})")]
22    TooMuchData(usize),
23    /// An io error from the underlying codec implementation
24    #[error(transparent)]
25    CodecError(#[from] io::Error),
26}
27
28/// Error when receiving bogus data from the other end
29#[derive(Debug, Error)]
30#[error("{msg}")]
31pub struct InvalidData {
32    /// A human readable message
33    pub msg: &'static str,
34    /// The data that was invalid
35    pub offending_bytes: BytesMut,
36}
37
38impl InvalidData {
39    /// Create a new `InvalidData` error
40    #[must_use]
41    pub fn new(msg: &'static str, offending_bytes: BytesMut) -> Self {
42        Self {
43            msg,
44            offending_bytes,
45        }
46    }
47}
48
49pub const STAGE_DECODING: &str = "decoding";
50// pub const STAGE_ENCODING: &str = "encoding";
51
52/// Raised when definitely more data is necessary
53#[derive(Debug, Error)]
54#[error("{stage} {item}: expected '{expected}' bytes but got only '{got}': {msg}")]
55pub struct NotEnoughData {
56    /// The stage at which we are missing data
57    pub stage: &'static str,
58    /// The item that is missing data to wrok
59    pub item: &'static str,
60    /// Human readable message
61    pub msg: &'static str,
62    /// How many bytes where expected
63    pub expected: usize,
64    /// How many bytes where available
65    pub got: usize,
66    /// The problematic bytes
67    pub buffer: BytesMut,
68}
69
70impl NotEnoughData {
71    /// Create a new `NotEnoughData` error
72    #[must_use]
73    pub fn new(
74        stage: &'static str,
75        item: &'static str,
76        msg: &'static str,
77        expected: usize,
78        got: usize,
79        buffer: BytesMut,
80    ) -> Self {
81        Self {
82            stage,
83            item,
84            msg,
85            expected,
86            got,
87            buffer,
88        }
89    }
90}