1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
use std::{error::Error as StdError, fmt, io};
use crate::SharedString;
pub type BoxedError = Box<dyn std::error::Error + Send + Sync + 'static>;
#[derive(Debug)]
pub(crate) enum ErrorKind {
NoDefaultValue,
Io(io::Error),
Conversion(BoxedError),
Other(BoxedError),
}
impl From<io::Error> for ErrorKind {
fn from(err: io::Error) -> Self {
Self::Io(err)
}
}
impl From<BoxedError> for ErrorKind {
fn from(err: BoxedError) -> Self {
Self::Conversion(err)
}
}
impl ErrorKind {
pub fn or(self, other: Self) -> Self {
use ErrorKind::*;
match (self, other) {
(NoDefaultValue, other) => other,
(Io(_), other @ Conversion(_)) => other,
(Io(err), other @ Io(_)) if err.kind() == io::ErrorKind::NotFound => other,
(this, _) => this,
}
}
}
#[derive(Debug)]
struct NoDefaultValueError;
impl fmt::Display for NoDefaultValueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("the asset has neither extension nor default value")
}
}
impl StdError for NoDefaultValueError {}
struct ErrorRepr {
id: SharedString,
kind: ErrorKind,
}
pub struct Error(Box<ErrorRepr>);
impl Error {
#[cold]
pub(crate) fn from_io(id: SharedString, err: io::Error) -> Self {
Self::from_kind(id, ErrorKind::Io(err))
}
pub(crate) fn from_kind(id: SharedString, kind: ErrorKind) -> Self {
Self(Box::new(ErrorRepr { id, kind }))
}
#[cold]
pub(crate) fn new(id: SharedString, err: BoxedError) -> Self {
Self::from_kind(id, ErrorKind::Other(err))
}
#[inline]
pub fn id(&self) -> &SharedString {
&self.0.id
}
pub fn reason(&self) -> &(dyn StdError + 'static) {
match &self.0.kind {
ErrorKind::Io(err) => err,
ErrorKind::Conversion(err) | ErrorKind::Other(err) => &**err,
ErrorKind::NoDefaultValue => &NoDefaultValueError,
}
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Error")
.field("id", &self.0.id)
.field("kind", &self.0.kind)
.finish()
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("failed to load \"{}\"", self.id()))
}
}
impl std::error::Error for Error {
#[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(self.reason())
}
}