oxigdal_core/error/
extensions.rs1use super::types::OxiGdalError;
4
5#[cfg(not(feature = "std"))]
6use alloc::string::String;
7#[cfg(not(feature = "std"))]
8use alloc::vec::Vec;
9
10#[macro_export]
27macro_rules! ensure {
28 ($cond:expr, $err:expr) => {
29 if !($cond) {
30 return Err($crate::error::OxiGdalError::$err.into());
31 }
32 };
33 ($cond:expr, $err:ident { $($field:ident: $value:expr),* $(,)? }) => {
34 if !($cond) {
35 return Err($crate::error::OxiGdalError::$err {
36 $($field: $value),*
37 }.into());
38 }
39 };
40}
41
42pub trait ResultExt<T> {
44 fn context(self, msg: impl Into<String>) -> crate::error::Result<T>;
46
47 fn with_context<F>(self, f: F) -> crate::error::Result<T>
49 where
50 F: FnOnce() -> String;
51}
52
53impl<T> ResultExt<T> for crate::error::Result<T> {
54 fn context(self, msg: impl Into<String>) -> crate::error::Result<T> {
55 self.map_err(|_| OxiGdalError::Internal {
56 message: msg.into(),
57 })
58 }
59
60 fn with_context<F>(self, f: F) -> crate::error::Result<T>
61 where
62 F: FnOnce() -> String,
63 {
64 self.map_err(|_| OxiGdalError::Internal { message: f() })
65 }
66}
67
68#[derive(Debug)]
70pub struct ErrorAggregator {
71 errors: Vec<OxiGdalError>,
72}
73
74impl ErrorAggregator {
75 pub fn new() -> Self {
77 Self { errors: Vec::new() }
78 }
79
80 pub fn add(&mut self, error: OxiGdalError) {
82 self.errors.push(error);
83 }
84
85 pub fn add_result<T>(&mut self, result: crate::error::Result<T>) -> Option<T> {
87 match result {
88 Ok(value) => Some(value),
89 Err(error) => {
90 self.add(error);
91 None
92 }
93 }
94 }
95
96 pub fn has_errors(&self) -> bool {
98 !self.errors.is_empty()
99 }
100
101 pub fn count(&self) -> usize {
103 self.errors.len()
104 }
105
106 pub fn into_result(self) -> crate::error::Result<()> {
108 if self.errors.is_empty() {
109 Ok(())
110 } else {
111 let count = self.errors.len();
112 let first = &self.errors[0];
113 Err(OxiGdalError::Internal {
114 message: format!(
115 "Multiple errors occurred ({} total). First error: {}",
116 count, first
117 ),
118 })
119 }
120 }
121
122 pub fn into_errors(self) -> Vec<OxiGdalError> {
124 self.errors
125 }
126}
127
128impl Default for ErrorAggregator {
129 fn default() -> Self {
130 Self::new()
131 }
132}