ipld_nostd/cid/
error.rs

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