use core::fmt::Display;
use core::fmt::Formatter;
use core::fmt::Result as FmtResult;
use core::result::Result as StdResult;
use hex::FromHexError as HexError;
use std::error::Error as StdError;
use std::io::Error as IoError;
use url::ParseError as UrlError;
use url::Url;
pub(crate) type Result<T> = StdResult<T, Error>;
#[derive(Debug)]
pub enum Error {
BadLength { expected: usize, actual: usize },
InvalidScheme(Url),
MissingObjectType(Url),
MissingHashAlgorithm(Url),
MissingHash(Url),
UnknownObjectType(String),
MismatchedObjectType { expected: String, observed: String },
MismatchedHashAlgorithm { expected: String, observed: String },
UnexpectedHashLength { expected: usize, observed: usize },
InvalidHex(HexError),
Url(UrlError),
Io(IoError),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
Error::BadLength { expected, actual } => {
write!(f, "expected length {}, actual length {}", expected, actual)
}
Error::InvalidScheme(url) => write!(f, "invalid scheme in URL '{}'", url.scheme()),
Error::MissingObjectType(url) => write!(f, "missing object type in URL '{}'", url),
Error::MissingHashAlgorithm(url) => {
write!(f, "missing hash algorithm in URL '{}'", url)
}
Error::MissingHash(url) => write!(f, "missing hash in URL '{}'", url),
Error::UnknownObjectType(s) => write!(f, "unknown object type '{}'", s),
Error::MismatchedObjectType { expected, observed } => write!(
f,
"mismatched object type; expected '{}', got '{}'",
expected, observed
),
Error::MismatchedHashAlgorithm { expected, observed } => write!(
f,
"mismatched hash algorithm; expected '{}', got '{}'",
expected, observed
),
Error::UnexpectedHashLength { expected, observed } => {
write!(
f,
"unexpected hash length; expected '{}', got '{}'",
expected, observed
)
}
Error::InvalidHex(_) => write!(f, "invalid hex string"),
Error::Url(e) => write!(f, "{}", e),
Error::Io(e) => write!(f, "{}", e),
}
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
Error::BadLength { .. }
| Error::InvalidScheme(_)
| Error::MissingObjectType(_)
| Error::MissingHashAlgorithm(_)
| Error::MissingHash(_)
| Error::UnknownObjectType(_)
| Error::MismatchedObjectType { .. }
| Error::MismatchedHashAlgorithm { .. }
| Error::UnexpectedHashLength { .. } => None,
Error::InvalidHex(e) => Some(e),
Error::Url(e) => Some(e),
Error::Io(e) => Some(e),
}
}
}
impl From<HexError> for Error {
fn from(e: HexError) -> Error {
Error::InvalidHex(e)
}
}
impl From<UrlError> for Error {
fn from(e: UrlError) -> Error {
Error::Url(e)
}
}
impl From<IoError> for Error {
fn from(e: IoError) -> Error {
Error::Io(e)
}
}