use std::borrow::Cow;
use std::io::ErrorKind;
pub use std::io::Error as IoError;
pub use std::io::Result as IoResult;
use std::convert::TryFrom;
use std::error;
use std::fmt;
use std::num::TryFromIntError;
pub type Result<T> = std::result::Result<T, Error>;
pub type UnitResult = Result<()>;
#[derive(Debug)]
pub enum Error {
Aborted, NotSupported(Cow<'static, str>),
Invalid(Cow<'static, str>),
Io(IoError),
}
impl Error {
pub(crate) fn invalid(message: impl Into<Cow<'static, str>>) -> Self {
Error::Invalid(message.into())
}
pub(crate) fn unsupported(message: impl Into<Cow<'static, str>>) -> Self {
Error::NotSupported(message.into())
}
}
impl From<IoError> for Error {
fn from(error: IoError) -> Self {
if error.kind() == ErrorKind::UnexpectedEof {
Error::invalid("reference to missing bytes")
}
else {
Error::Io(error)
}
}
}
impl From<TryFromIntError> for Error {
fn from(_: TryFromIntError) -> Self {
Error::invalid("invalid size")
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
Error::Io(ref err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Io(err) => err.fmt(formatter),
Error::NotSupported(message) => write!(formatter, "not supported: {}", message),
Error::Invalid(message) => write!(formatter, "invalid: {}", message),
Error::Aborted => write!(formatter, "cancelled"),
}
}
}
#[inline]
pub(crate) fn i32_to_usize(value: i32, error_message: &'static str) -> Result<usize> {
usize::try_from(value).map_err(|_| Error::invalid(error_message))
}
#[inline]
pub(crate) fn usize_to_u16(value: usize) -> Result<u16> {
Ok(u16::try_from(value)?)
}
#[inline]
pub(crate) fn u64_to_usize(value: u64) -> usize {
usize::try_from(value).expect("(u64 as usize) overflowed")
}
#[inline]
pub(crate) fn u32_to_usize(value: u32) -> usize {
usize::try_from(value).expect("(u32 as usize) overflowed")
}
#[inline]
pub(crate) fn usize_to_i32(value: usize) -> i32 {
i32::try_from(value).expect("(usize as i32) overflowed")
}
#[inline]
pub(crate) fn usize_to_u64(value: usize) -> u64 {
u64::try_from(value).expect("(usize as u64) overflowed")
}