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
#[cfg(not(feature = "std"))]
use core2::{error::Error as StdError, io::Error as IoError};
#[cfg(feature = "std")]
use std::{error::Error as StdError, io::Error as IoError};

use unsigned_varint::decode::Error as DecodeError;
#[cfg(feature = "std")]
use unsigned_varint::io::ReadError;

/// Multihash error.
#[derive(Debug)]
pub enum Error {
    /// Io error.
    Io(IoError),
    /// Unsupported multihash code.
    UnsupportedCode(u64),
    /// Invalid multihash size.
    InvalidSize(u64),
    /// Invalid varint.
    Varint(DecodeError),
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match self {
            Self::Io(err) => write!(f, "{}", err),
            Self::UnsupportedCode(code) => write!(f, "Unsupported multihash code {}.", code),
            Self::InvalidSize(size) => write!(f, "Invalid multihash size {}.", size),
            Self::Varint(err) => write!(f, "{}", err),
        }
    }
}

impl StdError for Error {}

impl From<IoError> for Error {
    fn from(err: IoError) -> Self {
        Self::Io(err)
    }
}

#[cfg(feature = "std")]
impl From<ReadError> for Error {
    fn from(err: ReadError) -> Self {
        match err {
            ReadError::Io(err) => Self::Io(err),
            ReadError::Decode(err) => Self::Varint(err),
            _ => unreachable!(),
        }
    }
}

/// Multihash result.
pub type Result<T> = core::result::Result<T, Error>;