1use std::{error, fmt, io, net, num, str, string};
2use unsigned_varint::decode;
3
4pub type Result<T> = ::std::result::Result<T, Error>;
5
6#[derive(Debug)]
8#[non_exhaustive]
9pub enum Error {
10 DataLessThanLen,
11 InvalidMultiaddr,
12 InvalidProtocolString,
13 InvalidUvar(decode::Error),
14 ParsingError(Box<dyn error::Error + Send + Sync>),
15 UnknownProtocolId(u32),
16 UnknownProtocolString(String),
17}
18
19impl fmt::Display for Error {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 match self {
22 Error::DataLessThanLen => f.write_str("we have less data than indicated by length"),
23 Error::InvalidMultiaddr => f.write_str("invalid multiaddr"),
24 Error::InvalidProtocolString => f.write_str("invalid protocol string"),
25 Error::InvalidUvar(e) => write!(f, "failed to decode unsigned varint: {e}"),
26 Error::ParsingError(e) => write!(f, "failed to parse: {e}"),
27 Error::UnknownProtocolId(id) => write!(f, "unknown protocol id: {id}"),
28 Error::UnknownProtocolString(string) => {
29 write!(f, "unknown protocol string: {string}")
30 }
31 }
32 }
33}
34
35impl error::Error for Error {
36 #[inline]
37 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
38 if let Error::ParsingError(e) = self {
39 Some(&**e)
40 } else {
41 None
42 }
43 }
44}
45
46impl From<io::Error> for Error {
47 fn from(err: io::Error) -> Error {
48 Error::ParsingError(err.into())
49 }
50}
51
52impl From<multihash::Error> for Error {
53 fn from(err: multihash::Error) -> Error {
54 Error::ParsingError(err.into())
55 }
56}
57
58impl From<multibase::Error> for Error {
59 fn from(err: multibase::Error) -> Error {
60 Error::ParsingError(err.into())
61 }
62}
63
64impl From<net::AddrParseError> for Error {
65 fn from(err: net::AddrParseError) -> Error {
66 Error::ParsingError(err.into())
67 }
68}
69
70impl From<num::ParseIntError> for Error {
71 fn from(err: num::ParseIntError) -> Error {
72 Error::ParsingError(err.into())
73 }
74}
75
76impl From<string::FromUtf8Error> for Error {
77 fn from(err: string::FromUtf8Error) -> Error {
78 Error::ParsingError(err.into())
79 }
80}
81
82impl From<str::Utf8Error> for Error {
83 fn from(err: str::Utf8Error) -> Error {
84 Error::ParsingError(err.into())
85 }
86}
87
88impl From<decode::Error> for Error {
89 fn from(e: decode::Error) -> Error {
90 Error::InvalidUvar(e)
91 }
92}