use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
InvalidArgument,
OutOfRange,
Length,
Overflow,
OutOfMemory,
Other,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Error {
kind: ErrorKind,
message: String,
}
impl Error {
pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Error {
kind,
message: message.into(),
}
}
pub(crate) fn invalid(message: impl Into<String>) -> Self {
Error::new(ErrorKind::InvalidArgument, message)
}
pub fn kind(&self) -> ErrorKind {
self.kind
}
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for Error {}
impl From<cxx::Exception> for Error {
fn from(e: cxx::Exception) -> Self {
let what = e.what();
let kind = match what.as_bytes().first() {
Some(b'I') => ErrorKind::InvalidArgument,
Some(b'R') => ErrorKind::OutOfRange,
Some(b'L') => ErrorKind::Length,
Some(b'O') => ErrorKind::Overflow,
Some(b'M') => ErrorKind::OutOfMemory,
_ => ErrorKind::Other,
};
Error::new(kind, what.get(1..).unwrap_or(""))
}
}
pub type Result<T> = std::result::Result<T, Error>;