rustybit_serde_bencode/
error.rs

1#[derive(Debug)]
2pub struct Error {
3    pub kind: ErrorKind,
4    pub position: Option<usize>,
5}
6
7impl Error {
8    pub fn set_position(mut self, position: usize) -> Self {
9        self.position = Some(position);
10        self
11    }
12}
13
14impl std::fmt::Display for Error {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        if let Some(pos) = self.position {
17            write!(f, "Error at position {}: {}", pos, self.kind)
18        } else {
19            write!(f, "Error: {}", self.kind)
20        }
21    }
22}
23
24impl std::error::Error for Error {}
25
26impl serde::de::Error for Error {
27    fn custom<T>(msg: T) -> Self
28    where
29        T: std::fmt::Display,
30    {
31        ErrorKind::Custom(msg.to_string()).into()
32    }
33}
34
35impl serde::ser::Error for Error {
36    fn custom<T>(msg: T) -> Self
37    where
38        T: std::fmt::Display,
39    {
40        ErrorKind::Custom(msg.to_string()).into()
41    }
42}
43
44impl From<ErrorKind> for Error {
45    fn from(value: ErrorKind) -> Self {
46        Error {
47            kind: value,
48            position: Default::default(),
49        }
50    }
51}
52
53#[derive(Debug)]
54pub enum ErrorKind {
55    Custom(String),
56    UnexpectedEof(&'static str),
57    BadInputData(&'static str),
58    Unsupported(&'static str),
59}
60
61impl std::fmt::Display for ErrorKind {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        match self {
64            ErrorKind::Custom(msg) => write!(f, "{}", msg),
65            ErrorKind::UnexpectedEof(expected) => {
66                write!(f, "Unexpected EOF encounetered, expected \"{}\" instead", expected)
67            }
68            ErrorKind::BadInputData(msg) => write!(f, "Input data is broken: {}", msg),
69            ErrorKind::Unsupported(msg) => write!(f, "Bencode doesn't support {}", msg),
70        }
71    }
72}