1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/// Type alias to use this library's [`Error`] type in a `Result`.
pub type Result<T> = core::result::Result<T, Error>;

/// Error types
#[derive(Debug)]
pub enum Error {
    /// Unknown CID codec.
    UnknownCodec,
    /// Input data is too short.
    InputTooShort,
    /// Multibase or multihash codec failure
    ParsingError,
    /// Invalid CID version.
    InvalidCidVersion,
    /// Invalid CIDv0 codec.
    InvalidCidV0Codec,
    /// Invalid CIDv0 multihash.
    InvalidCidV0Multihash,
    /// Invalid CIDv0 base encoding.
    InvalidCidV0Base,
    /// Varint decode failure.
    VarIntDecodeError,
    /// Io error.
    #[cfg(feature = "std")]
    Io(std::io::Error),
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        use self::Error::*;
        let error = match self {
            UnknownCodec => "Unknown codec",
            InputTooShort => "Input too short",
            ParsingError => "Failed to parse multihash",
            InvalidCidVersion => "Unrecognized CID version",
            InvalidCidV0Codec => "CIDv0 requires a DagPB codec",
            InvalidCidV0Multihash => "CIDv0 requires a Sha-256 multihash",
            InvalidCidV0Base => "CIDv0 requires a Base58 base",
            VarIntDecodeError => "Failed to decode unsigned varint format",
            #[cfg(feature = "std")]
            Io(err) => return write!(f, "{}", err),
        };

        f.write_str(error)
    }
}

#[cfg(feature = "std")]
impl From<multibase::Error> for Error {
    fn from(_: multibase::Error) -> Error {
        Error::ParsingError
    }
}

impl From<tiny_multihash::Error> for Error {
    fn from(_: tiny_multihash::Error) -> Error {
        Error::ParsingError
    }
}

impl From<unsigned_varint::decode::Error> for Error {
    fn from(_: unsigned_varint::decode::Error) -> Self {
        Self::VarIntDecodeError
    }
}

#[cfg(feature = "std")]
impl From<unsigned_varint::io::ReadError> for Error {
    fn from(err: unsigned_varint::io::ReadError) -> Self {
        use unsigned_varint::io::ReadError::*;
        match err {
            Io(err) => Self::Io(err),
            _ => Self::VarIntDecodeError,
        }
    }
}

#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        Self::Io(err)
    }
}