bde/
error.rs

1use core::{fmt::Display, str::Utf8Error};
2use serde::{de, ser};
3
4pub type Result<T, E = Error> = core::result::Result<T, E>;
5
6#[derive(Debug, thiserror::Error)]
7pub enum Error {
8    #[error("{0}")]
9    Serde(String),
10    #[error("Unexpected end of file")]
11    Eof,
12    #[error("Trailing bytes")]
13    TrailingBytes,
14    #[error("Syntax error")]
15    Syntax,
16    #[error("Leading zeros are forbiden")]
17    LeadingZero,
18    #[error("Negative zero is not a valid bencode number")]
19    NegativeZero,
20    #[error("Invalid type")]
21    InvalidType,
22    #[error("Unexpected Token {found} at index {index}, expected {expected}")]
23    UnexpectedToken {
24        expected: &'static str,
25        found: u8,
26        index: usize,
27    },
28    #[error("Error while parsing utf8 value")]
29    Utf8(#[from] Utf8Error),
30    #[error("Io Error")]
31    Io(#[from] std::io::Error),
32    #[error("Unsupported type \"{0}\"")]
33    Unsupported(&'static str),
34    /// Unexpected end of file while parsing a byte string.
35    ///
36    /// This usually happens when the specified length is incorrect.
37    #[error("Unexpected end of file while parsing a byte string")]
38    EofWhileParsingByteString,
39
40    #[error("Expected a dictionary, found a byte string instead")]
41    ExpectedDictionaryFoundByteString,
42    #[error("Expected a dictionary, found an integer instead")]
43    ExpectedDictionaryFoundInteger,
44    #[error("Expected a dictionary, found a list instead")]
45    ExpectedDictionaryFoundList,
46
47    #[error("Unsorted keys")]
48    UnsortedKeys,
49
50    #[error("Integer out of bound")]
51    OutOfBound,
52
53    #[error("Map key must be a byte string")]
54    MapKeyMustBeByteString,
55}
56
57impl Error {
58    pub const fn unexpected_token(expected: &'static str, found: u8, index: usize) -> Self {
59        Self::UnexpectedToken {
60            expected,
61            found,
62            index,
63        }
64    }
65}
66
67impl ser::Error for Error {
68    fn custom<T: Display>(msg: T) -> Self {
69        Error::Serde(msg.to_string())
70    }
71}
72
73impl de::Error for Error {
74    fn custom<T: Display>(msg: T) -> Self {
75        Error::Serde(msg.to_string())
76    }
77}