tiny_cid/
error.rs

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