bevy_reflect_derive/
result_sifter.rs

1/// Helper struct used to process an iterator of `Result<Vec<T>, syn::Error>`,
2/// combining errors into one along the way.
3pub(crate) struct ResultSifter<T> {
4    items: Vec<T>,
5    errors: Option<syn::Error>,
6}
7
8impl<T> Default for ResultSifter<T> {
9    fn default() -> Self {
10        Self {
11            items: Vec::new(),
12            errors: None,
13        }
14    }
15}
16
17impl<T> ResultSifter<T> {
18    /// Sift the given result, combining errors if necessary.
19    pub fn sift(&mut self, result: Result<T, syn::Error>) {
20        match result {
21            Ok(data) => self.items.push(data),
22            Err(err) => {
23                if let Some(ref mut errors) = self.errors {
24                    errors.combine(err);
25                } else {
26                    self.errors = Some(err);
27                }
28            }
29        }
30    }
31
32    /// Associated method that provides a convenient implementation for [`Iterator::fold`].
33    pub fn fold(mut sifter: Self, result: Result<T, syn::Error>) -> Self {
34        sifter.sift(result);
35        sifter
36    }
37
38    /// Complete the sifting process and return the final result.
39    pub fn finish(self) -> Result<Vec<T>, syn::Error> {
40        if let Some(errors) = self.errors {
41            Err(errors)
42        } else {
43            Ok(self.items)
44        }
45    }
46}