sp_cid/
error.rs

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