|
85 | 85 | //! and `CollectAllErrors::collect_all_errors` for collecting errors from iterators. |
86 | 86 |
|
87 | 87 | use crate::map::HashSet; |
88 | | -use std::hash::Hash; |
| 88 | +use std::{fmt, hash::Hash}; |
89 | 89 |
|
90 | 90 | /// A non-empty stream of errors. |
91 | 91 | /// |
@@ -115,6 +115,41 @@ use std::hash::Hash; |
115 | 115 | pub struct ErrorStream<E>(smallvec::SmallVec<[E; 1]>); |
116 | 116 |
|
117 | 117 | impl<E> ErrorStream<E> { |
| 118 | + /// Build an error stream from a non-empty collection. |
| 119 | + /// If the collection is empty, panic. |
| 120 | + pub fn expect_nonempty<I: IntoIterator<Item = E>>(errors: I) -> Self { |
| 121 | + let mut errors = errors.into_iter(); |
| 122 | + let first = errors.next().expect("expected at least one error"); |
| 123 | + let mut stream = Self::from(first); |
| 124 | + stream.extend(errors); |
| 125 | + stream |
| 126 | + } |
| 127 | + |
| 128 | + /// Add some extra errors to a result. |
| 129 | + /// |
| 130 | + /// If there are no errors, the result is not modified. |
| 131 | + /// If there are errors, and the result is `Err`, the errors are added to the stream. |
| 132 | + /// If there are errors, and the result is `Ok`, the `Ok` value is discarded, and the errors are returned in a stream. |
| 133 | + pub fn add_extra_errors<T>( |
| 134 | + result: Result<T, ErrorStream<E>>, |
| 135 | + extra_errors: impl IntoIterator<Item = E>, |
| 136 | + ) -> Result<T, ErrorStream<E>> { |
| 137 | + match result { |
| 138 | + Ok(value) => { |
| 139 | + let errors: SmallVec<[E; 1]> = extra_errors.into_iter().collect(); |
| 140 | + if errors.is_empty() { |
| 141 | + Ok(value) |
| 142 | + } else { |
| 143 | + Err(ErrorStream(errors)) |
| 144 | + } |
| 145 | + } |
| 146 | + Err(mut errors) => { |
| 147 | + errors.extend(extra_errors); |
| 148 | + Err(errors) |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + |
118 | 153 | /// Returns an iterator over the errors in the stream. |
119 | 154 | pub fn iter(&self) -> impl Iterator<Item = &E> { |
120 | 155 | self.0.iter() |
@@ -154,6 +189,15 @@ impl<E> ErrorStream<E> { |
154 | 189 | } |
155 | 190 | } |
156 | 191 | } |
| 192 | +impl<E: fmt::Display> fmt::Display for ErrorStream<E> { |
| 193 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 194 | + writeln!(f, "Errors occurred:")?; |
| 195 | + for error in self.iter() { |
| 196 | + writeln!(f, "{}\n", error)?; |
| 197 | + } |
| 198 | + Ok(()) |
| 199 | + } |
| 200 | +} |
157 | 201 |
|
158 | 202 | impl<E: Ord + Eq> ErrorStream<E> { |
159 | 203 | /// Sort and deduplicate the errors in the error stream. |
@@ -454,6 +498,7 @@ macro_rules! expect_error_matching ( |
454 | 498 | ); |
455 | 499 | // Make available in this module as well as crate root. |
456 | 500 | pub use expect_error_matching; |
| 501 | +use smallvec::SmallVec; |
457 | 502 |
|
458 | 503 | #[cfg(test)] |
459 | 504 | mod tests { |
|
0 commit comments