use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt;
use std::path::{Path, PathBuf};
pub struct Error(Box<Inner>);
struct Inner {
kind: ErrorKind,
message: Cow<'static, str>,
path: Option<PathBuf>,
format: Option<&'static str>,
source: Option<Box<dyn StdError + Send + Sync>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
UnknownFormat,
FeatureDisabled,
Unsupported,
Corrupt,
Truncated,
Empty,
MissingAsset,
LimitExceeded,
Io,
Invalid,
}
impl ErrorKind {
fn describe(self) -> &'static str {
match self {
Self::UnknownFormat => "unknown format",
Self::FeatureDisabled => "feature disabled",
Self::Unsupported => "unsupported",
Self::Corrupt => "corrupt data",
Self::Truncated => "truncated data",
Self::Empty => "nothing to convert",
Self::MissingAsset => "missing asset",
Self::LimitExceeded => "limit exceeded",
Self::Io => "i/o error",
Self::Invalid => "invalid argument",
}
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.describe())
}
}
impl Error {
#[must_use]
pub fn kind(&self) -> ErrorKind {
self.0.kind
}
#[must_use]
pub fn path(&self) -> Option<&Path> {
self.0.path.as_deref()
}
#[must_use]
pub fn format(&self) -> Option<&'static str> {
self.0.format
}
#[cold]
#[inline(never)]
pub(crate) fn new(kind: ErrorKind, message: impl Into<Cow<'static, str>>) -> Self {
let message = match message.into() {
Cow::Owned(s) => Cow::Owned(printable(s)),
m @ Cow::Borrowed(_) => m,
};
Self(Box::new(Inner {
kind,
message,
path: None,
format: None,
source: None,
}))
}
#[cold]
#[inline(never)]
pub(crate) fn from_args(kind: ErrorKind, args: fmt::Arguments<'_>) -> Self {
match args.as_str() {
Some(s) => Self::new(kind, s),
None => Self::new(kind, fmt::format(args)),
}
}
#[allow(dead_code, reason = "which readers use it depends on the enabled features")]
pub(crate) fn corrupt(message: impl Into<Cow<'static, str>>) -> Self {
Self::new(ErrorKind::Corrupt, message)
}
#[allow(dead_code, reason = "which readers use it depends on the enabled features")]
pub(crate) fn truncated(message: impl Into<Cow<'static, str>>) -> Self {
Self::new(ErrorKind::Truncated, message)
}
#[allow(dead_code, reason = "which readers use it depends on the enabled features")]
pub(crate) fn unsupported(message: impl Into<Cow<'static, str>>) -> Self {
Self::new(ErrorKind::Unsupported, message)
}
#[allow(dead_code, reason = "which readers use it depends on the enabled features")]
pub(crate) fn missing(message: impl Into<Cow<'static, str>>) -> Self {
Self::new(ErrorKind::MissingAsset, message)
}
#[cold]
#[inline(never)]
pub(crate) fn caused(
kind: ErrorKind,
message: impl Into<Cow<'static, str>>,
source: impl StdError + Send + Sync + 'static,
) -> Self {
let mut e = Self::new(kind, message);
e.0.source = Some(Box::new(source));
e
}
#[cold]
#[must_use]
pub(crate) fn at(mut self, path: &Path) -> Self {
if self.0.path.is_none() {
self.0.path = Some(path.to_path_buf());
}
self
}
#[cold]
#[must_use]
#[allow(dead_code, reason = "only loading a model names its reader")]
pub(crate) fn in_format(mut self, format: &'static str) -> Self {
if self.0.format.is_none() {
self.0.format = Some(format);
}
self
}
#[cold]
#[inline(never)]
#[allow(dead_code, reason = "only reading from the file system uses it")]
pub(crate) fn asset(source: std::io::Error, path: &Path, what: impl Into<Cow<'static, str>>) -> Self {
let kind = match source.kind() {
std::io::ErrorKind::NotFound => ErrorKind::MissingAsset,
k => io_kind(k),
};
Self::caused(kind, what, source).at(path)
}
#[cold]
#[inline(never)]
#[must_use]
pub(crate) fn within(mut self, what: impl fmt::Display) -> Self {
let inner = &mut *self.0;
inner.message = Cow::Owned(printable(if inner.message.is_empty() {
what.to_string()
} else {
format!("{what}: {}", inner.message)
}));
self
}
#[cfg(test)]
pub(crate) fn message(&self) -> &str {
&self.0.message
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let inner = &*self.0;
if let Some(path) = &inner.path {
write!(f, "{}: ", path.display())?;
}
f.write_str(&inner.message)?;
if let Some(source) = &inner.source {
if !inner.message.is_empty() {
f.write_str(": ")?;
}
write!(f, "{source}")?;
}
Ok(())
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let inner = &*self.0;
let mut d = f.debug_struct("Error");
d.field("kind", &inner.kind).field("message", &inner.message);
if let Some(path) = &inner.path {
d.field("path", path);
}
if let Some(format) = inner.format {
d.field("format", &format);
}
if let Some(source) = &inner.source {
d.field("source", source);
}
d.finish()
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
self.0.source.as_ref().map(|s| &**s as &(dyn StdError + 'static))
}
}
impl From<std::io::Error> for Error {
#[cold]
fn from(e: std::io::Error) -> Self {
Self::caused(io_kind(e.kind()), "", e)
}
}
fn io_kind(kind: std::io::ErrorKind) -> ErrorKind {
match kind {
std::io::ErrorKind::UnexpectedEof => ErrorKind::Truncated,
std::io::ErrorKind::InvalidData => ErrorKind::Corrupt,
_ => ErrorKind::Io,
}
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub(crate) trait Foreign: StdError + Send + Sync + 'static {}
impl Foreign for std::io::Error {}
impl Foreign for std::num::ParseIntError {}
impl Foreign for std::num::ParseFloatError {}
impl Foreign for std::num::TryFromIntError {}
impl Foreign for std::array::TryFromSliceError {}
impl Foreign for std::str::Utf8Error {}
impl Foreign for std::string::FromUtf8Error {}
impl Foreign for std::collections::TryReserveError {}
impl Foreign for serde_json::Error {}
#[cfg(any(feature = "3mf", feature = "dae", feature = "usd", feature = "amf"))]
impl Foreign for zip::result::ZipError {}
#[cfg(any(feature = "3mf", feature = "dae", feature = "x3d", feature = "amf"))]
impl Foreign for quick_xml::Error {}
#[cfg(feature = "e57")]
impl Foreign for e57::Error {}
#[cfg(feature = "laz")]
impl Foreign for laz::LasZipError {}
#[cfg(feature = "draco")]
impl Foreign for draco_core::DracoError {}
#[cfg(feature = "usd")]
impl Foreign for openusd::Error {}
pub(crate) trait Context<T> {
fn context(self, kind: ErrorKind, what: impl Into<Cow<'static, str>>) -> Result<T>;
fn with_context<M: Into<Cow<'static, str>>>(self, kind: ErrorKind, what: impl FnOnce() -> M) -> Result<T>;
}
impl<T> Context<T> for Option<T> {
#[inline]
fn context(self, kind: ErrorKind, what: impl Into<Cow<'static, str>>) -> Result<T> {
match self {
Some(v) => Ok(v),
None => Err(Error::new(kind, what)),
}
}
#[inline]
fn with_context<M: Into<Cow<'static, str>>>(self, kind: ErrorKind, what: impl FnOnce() -> M) -> Result<T> {
match self {
Some(v) => Ok(v),
None => Err(Error::new(kind, what())),
}
}
}
impl<T, E: Foreign> Context<T> for std::result::Result<T, E> {
#[inline]
fn context(self, kind: ErrorKind, what: impl Into<Cow<'static, str>>) -> Result<T> {
match self {
Ok(v) => Ok(v),
Err(e) => Err(Error::caused(kind, what, e)),
}
}
#[inline]
fn with_context<M: Into<Cow<'static, str>>>(self, kind: ErrorKind, what: impl FnOnce() -> M) -> Result<T> {
match self {
Ok(v) => Ok(v),
Err(e) => Err(Error::caused(kind, what(), e)),
}
}
}
pub(crate) trait Within<T> {
#[allow(dead_code, reason = "which readers use it depends on the enabled features")]
fn within(self, what: impl fmt::Display) -> Result<T>;
fn with_within<D: fmt::Display>(self, what: impl FnOnce() -> D) -> Result<T>;
}
impl<T> Within<T> for Result<T> {
#[inline]
fn within(self, what: impl fmt::Display) -> Result<T> {
self.map_err(|e| e.within(what))
}
#[inline]
fn with_within<D: fmt::Display>(self, what: impl FnOnce() -> D) -> Result<T> {
self.map_err(|e| e.within(what()))
}
}
#[allow(dead_code, reason = "which readers use it depends on the enabled features")]
pub(crate) fn shown(text: &[u8]) -> String {
const MOST: usize = 32;
let text = String::from_utf8_lossy(text);
let mut cut: String = text.chars().take(MOST).collect();
if text.chars().nth(MOST).is_some() {
cut.push('…');
}
format!("{cut:?}")
}
pub(crate) fn printable(message: String) -> String {
if !message.chars().any(char::is_control) {
return message;
}
message
.chars()
.map(|c| {
if c.is_control() {
c.escape_debug().to_string()
} else {
c.to_string()
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
const _: () = {
const fn send_sync_static<T: Send + Sync + 'static>() {}
send_sync_static::<Error>();
assert!(size_of::<Error>() == size_of::<usize>());
assert!(size_of::<Result<()>>() == size_of::<usize>());
};
#[test]
fn constant_messages_are_borrowed() {
let e = Error::from_args(ErrorKind::Corrupt, format_args!("no triangles"));
assert!(matches!(e.0.message, Cow::Borrowed("no triangles")));
let n = 3;
let e = Error::from_args(ErrorKind::Corrupt, format_args!("{n} triangles"));
assert_eq!(e.message(), "3 triangles");
}
#[test]
fn display_has_the_path_message_and_source() {
let io = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
let e = Error::caused(ErrorKind::Io, "reading the MTL library", io).at(Path::new("a/b.mtl"));
assert_eq!(e.to_string(), "a/b.mtl: reading the MTL library: denied");
assert_eq!(e.path(), Some(Path::new("a/b.mtl")));
let e = Error::from(std::io::Error::other("gone"));
assert_eq!(e.to_string(), "gone");
assert_eq!(e.kind(), ErrorKind::Io);
assert!(e.source().is_some_and(|s| s.downcast_ref::<std::io::Error>().is_some()));
}
#[test]
fn io_end_of_data_is_truncated() {
let eof = std::io::Error::from(std::io::ErrorKind::UnexpectedEof);
assert_eq!(Error::from(eof).kind(), ErrorKind::Truncated);
let bad = std::io::Error::from(std::io::ErrorKind::InvalidData);
assert_eq!(Error::from(bad).kind(), ErrorKind::Corrupt);
}
#[test]
fn within_keeps_kind_path_and_source() {
let e = Error::caused(ErrorKind::Truncated, "chunk", std::io::Error::other("eof"))
.at(Path::new("m.3ds"))
.within("reading mesh 2");
assert_eq!(e.kind(), ErrorKind::Truncated);
assert_eq!(e.to_string(), "m.3ds: reading mesh 2: chunk: eof");
assert!(e.source().is_some());
}
#[test]
fn control_characters_are_escaped() {
let e = Error::new(ErrorKind::Corrupt, String::from("bad \u{1b}[31m name"));
assert_eq!(e.message(), "bad \\u{1b}[31m name");
}
}