Skip to main content

rostra_util_error/
fmt.rs

1use std::{error, fmt, result};
2
3pub struct FmtCompactError<'e, E>(pub &'e E);
4
5impl<E> fmt::Display for FmtCompactError<'_, E>
6where
7    E: error::Error,
8{
9    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10        let mut error = Some(self.0 as &dyn error::Error);
11
12        while let Some(err) = error {
13            f.write_fmt(format_args!("{err}"))?;
14            error = err.source();
15            if error.is_some() {
16                f.write_str(": ")?;
17            }
18        }
19
20        Ok(())
21    }
22}
23
24pub struct FmtCompactResult<'r, O, E>(pub &'r result::Result<O, E>);
25
26impl<O, E> fmt::Display for FmtCompactResult<'_, O, E>
27where
28    E: error::Error,
29    O: fmt::Display,
30{
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        match self.0 {
33            Ok(o) => o.fmt(f),
34            Err(e) => FmtCompactError(e).fmt(f),
35        }
36    }
37}
38
39pub trait FmtCompact {
40    type Report<'a>: fmt::Display
41    where
42        Self: 'a;
43    fn fmt_compact(&self) -> Self::Report<'_>;
44}
45
46impl<E> FmtCompact for E
47where
48    E: error::Error,
49{
50    type Report<'a>
51        = FmtCompactError<'a, E>
52    where
53        E: 'a;
54    fn fmt_compact(&self) -> Self::Report<'_> {
55        FmtCompactError(self)
56    }
57}