1use std::fmt;
13use std::io;
14use std::path::Path;
15
16pub struct Error {
29 inner: Box<Inner>,
31}
32
33pub type Result<T> = std::result::Result<T, Error>;
34
35#[derive(Default)]
36struct Inner {
37 sources: Vec<Box<dyn std::error::Error + Send + Sync + 'static>>,
38 messages: Vec<String>,
39 is_corruption: bool,
40 io_error_kind: Option<io::ErrorKind>,
41}
42
43impl Error {
44 pub fn is_corruption(&self) -> bool {
79 self.inner.is_corruption
80 }
81
82 pub fn io_error_kind(&self) -> io::ErrorKind {
83 self.inner.io_error_kind.unwrap_or(io::ErrorKind::Other)
84 }
85
86 pub(crate) fn message(mut self, message: impl ToString) -> Self {
90 self.inner.messages.push(message.to_string());
91 self
92 }
93
94 pub(crate) fn source(self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
95 self.source_dyn(Box::new(source))
96 }
97
98 pub(crate) fn source_dyn(
99 mut self,
100 source: Box<dyn std::error::Error + Send + Sync + 'static>,
101 ) -> Self {
102 if let Some(err) = source.downcast_ref::<Error>() {
104 if err.is_corruption() {
105 self = self.mark_corruption();
106 }
107 }
108
109 self.inner.sources.push(source);
110 self
111 }
112
113 pub(crate) fn mark_corruption(mut self) -> Self {
114 self.inner.is_corruption = true;
115 self
116 }
117
118 pub(crate) fn blank() -> Self {
119 Error {
120 inner: Default::default(),
121 }
122 }
123
124 #[inline(never)]
127 pub(crate) fn programming(message: impl ToString) -> Self {
128 Self::blank().message(format!("ProgrammingError: {}", message.to_string()))
129 }
130
131 #[inline(never)]
135 pub(crate) fn corruption(path: &Path, message: impl ToString) -> Self {
136 let message = format!("{:?}: {}", path, message.to_string());
137 Self::blank().mark_corruption().message(message)
138 }
139
140 #[inline(never)]
144 pub(crate) fn path(path: &Path, message: impl ToString) -> Self {
145 let message = format!("{:?}: {}", path, message.to_string());
146 Self::blank().message(message)
147 }
148
149 #[inline(never)]
151 pub(crate) fn wrap(
152 err: Box<dyn std::error::Error + Send + Sync + 'static>,
153 message: impl LazyToString,
154 ) -> Self {
155 Self::blank()
156 .message(message.to_string_costly())
157 .source_dyn(err)
158 }
159}
160
161impl From<&str> for Error {
163 fn from(s: &str) -> Self {
164 Self::blank().message(s)
165 }
166}
167
168impl<E: std::error::Error + Send + Sync + 'static> From<(&str, E)> for Error {
170 fn from(s: (&str, E)) -> Self {
171 Self::blank().message(s.0).source(s.1)
172 }
173}
174
175impl fmt::Display for Error {
176 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
177 let mut lines = Vec::new();
178 for message in &self.inner.messages {
179 lines.push(message.to_string());
180 }
181 if !self.inner.sources.is_empty() {
182 lines.push(format!("Caused by {} errors:", self.inner.sources.len()));
183 for source in &self.inner.sources {
184 lines.push(indent(format!("{source}"), 2, '-'));
185 }
186 }
187 write!(f, "{}", lines.join("\n"))
188 }
189}
190
191impl fmt::Debug for Error {
192 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193 let mut lines = Vec::new();
194 for message in &self.inner.messages {
195 lines.push(message.to_string());
196 }
197 if self.is_corruption() {
198 lines.push("(This error is considered as a data corruption)".to_string())
199 }
200 if !self.inner.sources.is_empty() {
201 lines.push(format!("Caused by {} errors:", self.inner.sources.len()));
202 for source in &self.inner.sources {
203 lines.push(indent(format!("{source:?}"), 2, '-'));
204 }
205 }
206 write!(f, "{}", lines.join("\n"))
207 }
208}
209
210fn indent(s: String, spaces: usize, first_line_prefix: char) -> String {
211 if spaces == 0 {
212 s
213 } else {
214 format!(
215 "{}{}{}",
216 first_line_prefix,
217 " ".repeat(spaces - 1),
218 s.lines()
219 .collect::<Vec<_>>()
220 .join(&format!("\n{}", " ".repeat(spaces)))
221 )
222 }
223}
224
225pub(crate) trait ResultExt<T> {
226 fn corruption(self) -> Self;
228
229 fn context<S: LazyToString>(self, message: S) -> Self;
231
232 fn source<E: std::error::Error + Send + Sync + 'static>(self, source: E) -> Self;
234}
235
236impl<T> ResultExt<T> for Result<T> {
237 fn corruption(self) -> Self {
238 self.map_err(|err| err.mark_corruption())
239 }
240
241 fn context<S: LazyToString>(self, message: S) -> Self {
242 self.map_err(|err| err.message(message.to_string_costly()))
243 }
244
245 fn source<E: std::error::Error + Send + Sync + 'static>(self, source: E) -> Self {
246 self.map_err(|err| err.source(source))
247 }
248}
249
250impl std::error::Error for Error {
251 }
257
258pub(crate) trait IoResultExt<T> {
259 fn context<TS: LazyToString>(self, path: &Path, message: TS) -> Result<T>;
267
268 fn infallible(self) -> Result<T>;
270}
271
272impl<T> IoResultExt<T> for std::io::Result<T> {
273 fn context<TS: LazyToString>(self, path: &Path, message: TS) -> Result<T> {
274 self.map_err(|err| {
275 use std::io::ErrorKind;
276 let kind = err.kind().clone();
277 let corruption = match kind {
278 ErrorKind::UnexpectedEof | ErrorKind::InvalidData => true,
282 _ => false,
283 };
284 let is_eperm = kind == ErrorKind::PermissionDenied;
285
286 let mut err = Error::blank().source(err).message(format!(
287 "{:?}: {}",
288 path,
289 message.to_string_costly()
290 ));
291 if corruption {
292 err = err.mark_corruption();
293 }
294 err.inner.io_error_kind = Some(kind);
295
296 if is_eperm {
298 #[cfg(unix)]
299 #[allow(clippy::redundant_closure_call)]
300 {
301 let add_stat_context = |path: &Path, err: Error| {
302 use std::os::unix::fs::MetadataExt;
303 if let Ok(meta) = path.metadata() {
304 let msg = format!(
305 "stat({:?}) = dev:{} ino:{} mode:0o{:o} uid:{} gid:{} mtime:{}",
306 path,
307 meta.dev(),
308 meta.ino(),
309 meta.mode(),
310 meta.uid(),
311 meta.gid(),
312 meta.mtime()
313 );
314 err.message(msg)
315 } else {
316 err
317 }
318 };
319 err = add_stat_context(path, err);
320 if let Some(parent) = path.parent() {
322 err = add_stat_context(parent, err);
323 }
324 }
325 }
326
327 err
328 })
329 }
330
331 fn infallible(self) -> Result<T> {
332 self.map_err(|err| Error::blank().source(err).message("Unexpected failure"))
333 }
334}
335
336pub(crate) trait LazyToString {
337 fn to_string_costly(&self) -> String;
338}
339
340impl LazyToString for &'static str {
342 fn to_string_costly(&self) -> String {
343 (*self).to_string()
344 }
345}
346
347impl<F: Fn() -> String> LazyToString for F {
348 fn to_string_costly(&self) -> String {
349 self()
350 }
351}
352
353#[cfg(test)]
354mod tests {
355 use super::*;
356
357 #[test]
358 fn test_error_format() {
359 let mut e = Error::blank();
360
361 assert_eq!(format!("{e}"), "");
362
363 e = e.message("Error Message 1");
366 e = e.message("Error Message 2");
367 assert_eq!(
368 format!("{e}"),
369 r#"Error Message 1
370Error Message 2"#
371 );
372
373 e = e.source(Error::blank().message("Inner Error 1"));
375 e = e.source(
376 Error::blank()
377 .message("Inner Error 2")
378 .source(Error::blank().message("Nested Error 1")),
379 );
380 assert_eq!(
381 format!("{e}"),
382 r#"Error Message 1
383Error Message 2
384Caused by 2 errors:
385- Inner Error 1
386- Inner Error 2
387 Caused by 1 errors:
388 - Nested Error 1"#
389 );
390
391 e = e.mark_corruption();
393 assert_eq!(
394 format!("{e:?}"),
395 r#"Error Message 1
396Error Message 2
397(This error is considered as a data corruption)
398Caused by 2 errors:
399- Inner Error 1
400- Inner Error 2
401 Caused by 1 errors:
402 - Nested Error 1"#
403 );
404 }
405
406 #[test]
407 fn test_result_ext() {
408 let result: Result<()> = Err(Error::blank()).corruption();
409 assert!(result.unwrap_err().is_corruption());
410 }
411
412 #[test]
413 fn test_inherit_corruption() {
414 assert!(!Error::blank().is_corruption());
415 assert!(!Error::blank().source(Error::blank()).is_corruption());
416 assert!(
417 Error::blank()
418 .source(Error::blank().mark_corruption())
419 .is_corruption()
420 );
421 assert!(
422 Error::blank()
423 .source(Error::blank().source(Error::blank().mark_corruption()))
424 .is_corruption()
425 );
426 }
427
428 #[test]
429 fn test_io_result_ext() {
430 let err = io_result().context(Path::new("a.txt"), "cannot open for reading");
431 assert_eq!(
432 format!("{}", err.unwrap_err()),
433 r#""a.txt": cannot open for reading
434Caused by 1 errors:
435- io::Error: something wrong happened"#
436 );
437
438 let name = "b.txt";
439 let err = io_result().context(Path::new(&name), || format!("cannot open {name}"));
440 assert_eq!(
441 format!("{}", err.unwrap_err()),
442 r#""b.txt": cannot open b.txt
443Caused by 1 errors:
444- io::Error: something wrong happened"#
445 );
446 }
447
448 fn io_result() -> std::io::Result<()> {
449 Err(std::io::Error::other("io::Error: something wrong happened"))
450 }
451}