#[derive(Debug)]
pub enum Error {
Io(std::io::Error),
Decode(DecodeError),
Encode(String),
Unsupported(String),
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::Io(e) => write!(f, "io error: {e}"),
Error::Decode(d) => {
write!(f, "decode error: {}", d.message)?;
if let Some(m) = d.marker {
write!(f, " (marker {m:#06X})")?;
}
if let Some(b) = d.box_ {
write!(f, " (box {})", String::from_utf8_lossy(&b))?;
}
if let Some(p) = d.pos {
write!(f, " (at byte {p})")?;
}
Ok(())
}
Error::Encode(s) => write!(f, "encode error: {s}"),
Error::Unsupported(s) => write!(f, "unsupported: {s}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io(e) => Some(e),
_ => None,
}
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::Io(e)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DecodeError {
pub message: String,
pub marker: Option<u16>,
pub box_: Option<[u8; 4]>,
pub pos: Option<u64>,
}
impl From<String> for DecodeError {
fn from(message: String) -> Self {
DecodeError {
message,
..Default::default()
}
}
}
impl From<&str> for DecodeError {
fn from(message: &str) -> Self {
DecodeError {
message: message.into(),
..Default::default()
}
}
}
pub(crate) fn catch_codec_panic<T>(is_decode: bool, f: impl FnOnce() -> Result<T>) -> Result<T> {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(result) => result,
Err(payload) => {
let detail = payload
.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "unknown panic".to_string());
if is_decode {
Err(Error::Decode(
format!("internal decoder panic: {detail}").into(),
))
} else {
Err(Error::Encode(format!("internal encoder panic: {detail}")))
}
}
}
}
pub type Result<T, E = Error> = core::result::Result<T, E>;