cid/
error.rs

1use core::fmt;
2
3#[cfg(feature = "std")]
4use std::io;
5
6#[cfg(not(feature = "std"))]
7use core2::io;
8
9/// Type alias to use this library's [`Error`] type in a `Result`.
10pub type Result<T> = core::result::Result<T, Error>;
11
12/// Error types
13#[derive(Debug)]
14pub enum Error {
15    /// Unknown CID codec.
16    UnknownCodec,
17    /// Input data is too short.
18    InputTooShort,
19    /// Multibase or multihash codec failure
20    ParsingError,
21    /// Invalid CID version.
22    InvalidCidVersion,
23    /// Invalid CIDv0 codec.
24    InvalidCidV0Codec,
25    /// Invalid CIDv0 multihash.
26    InvalidCidV0Multihash,
27    /// Invalid CIDv0 base encoding.
28    InvalidCidV0Base,
29    /// Varint decode failure.
30    VarIntDecodeError,
31    /// Io error.
32    Io(io::Error),
33    /// Invalid explicit CIDv0.
34    InvalidExplicitCidV0,
35}
36
37#[cfg(feature = "std")]
38impl std::error::Error for Error {}
39
40impl fmt::Display for Error {
41    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
42        use self::Error::*;
43        let error = match self {
44            UnknownCodec => "Unknown codec",
45            InputTooShort => "Input too short",
46            ParsingError => "Failed to parse multihash",
47            InvalidCidVersion => "Unrecognized CID version",
48            InvalidCidV0Codec => "CIDv0 requires a DagPB codec",
49            InvalidCidV0Multihash => "CIDv0 requires a Sha-256 multihash",
50            InvalidCidV0Base => "CIDv0 requires a Base58 base",
51            VarIntDecodeError => "Failed to decode unsigned varint format",
52            Io(err) => return write!(f, "{}", err),
53            InvalidExplicitCidV0 => "CIDv0 cannot be specified in CIDv1 format",
54        };
55
56        f.write_str(error)
57    }
58}
59
60#[cfg(feature = "alloc")]
61impl From<multibase::Error> for Error {
62    fn from(_: multibase::Error) -> Error {
63        Error::ParsingError
64    }
65}
66
67impl From<multihash::Error> for Error {
68    fn from(_: multihash::Error) -> Error {
69        Error::ParsingError
70    }
71}
72
73impl From<unsigned_varint::decode::Error> for Error {
74    fn from(_: unsigned_varint::decode::Error) -> Self {
75        Error::VarIntDecodeError
76    }
77}
78
79#[cfg(feature = "std")]
80impl From<unsigned_varint::io::ReadError> for Error {
81    fn from(err: unsigned_varint::io::ReadError) -> Self {
82        use unsigned_varint::io::ReadError::*;
83        match err {
84            Io(err) => Self::Io(err),
85            _ => Self::VarIntDecodeError,
86        }
87    }
88}
89
90impl From<io::Error> for Error {
91    fn from(err: io::Error) -> Self {
92        Self::Io(err)
93    }
94}