altrios_core/
combo_error.rs1use std::fmt::{Debug, Display};
2use std::ops::{Deref, DerefMut};
3
4#[derive(Debug, PartialEq, Eq, Clone)]
6pub struct ComboError<E: Display> {
7 layer: usize,
8 error: E,
9}
10
11impl<E: Debug + Display> ComboError<E> {
12 pub fn new(error: E) -> Self {
13 Self { layer: 0, error }
14 }
15}
16
17impl<E: Debug + Display> Deref for ComboError<E> {
18 type Target = E;
19 fn deref(&self) -> &E {
20 &self.error
21 }
22}
23
24impl<E: Debug + Display> DerefMut for ComboError<E> {
25 fn deref_mut(&mut self) -> &mut E {
26 &mut self.error
27 }
28}
29
30pub struct ComboErrors<E: Debug + Display>(Vec<ComboError<E>>);
31
32impl<E: Debug + Display> ComboErrors<E> {
33 #[inline]
34 pub fn new() -> Self {
35 ComboErrors(vec![])
36 }
37
38 #[inline]
39 pub fn add_context(&mut self, error_add: E) {
40 for error in &mut self.0 {
41 error.layer += 1;
42 }
43 self.0.insert(0, ComboError::<E>::new(error_add));
44 }
45 #[inline]
46 pub fn push(&mut self, error_add: E) {
47 self.0.push(ComboError::<E>::new(error_add));
48 }
49
50 #[inline]
51 pub fn make_err(self) -> Result<(), Self> {
52 if self.is_empty() {
53 Ok(())
54 } else {
55 Err(self)
56 }
57 }
58}
59
60impl<E: Debug + Display> Default for ComboErrors<E> {
61 fn default() -> Self {
62 Self::new()
63 }
64}
65
66impl<E: Debug + Display> Deref for ComboErrors<E> {
67 type Target = Vec<ComboError<E>>;
68 fn deref(&self) -> &Vec<ComboError<E>> {
69 &self.0
70 }
71}
72impl<E: Debug + Display> DerefMut for ComboErrors<E> {
73 fn deref_mut(&mut self) -> &mut Vec<ComboError<E>> {
74 &mut self.0
75 }
76}
77impl<E: Debug + Display> std::error::Error for ComboErrors<E> {}
78
79impl<E: Debug + Display> Display for ComboErrors<E> {
80 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81 let bullet = "- ";
82 let tab = " ";
83 writeln!(f, "Combo error:")?;
84 for error in &self.0 {
85 writeln!(f, "{}{}{}", tab.repeat(error.layer), bullet, error.error)?;
86 }
87 Ok(())
88 }
89}
90
91impl<E: Debug + Display> Debug for ComboErrors<E> {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 let bullet = "- ";
94 let tab = " ";
95 writeln!(f, "Combo error:")?;
96 for error in &self.0 {
97 writeln!(f, "{}{}{:?}", tab.repeat(error.layer), bullet, error.error)?;
98 }
99 Ok(())
100 }
101}