Skip to main content

lunar_lib/
iterator_ext.rs

1pub trait IteratorExtensions: Iterator + Sized {
2    fn try_map<U, E, F>(self, f: F) -> Result<impl Iterator<Item = U>, E>
3    where
4        F: FnMut(Self::Item) -> Result<U, E>,
5    {
6        Ok(self.map(f).collect::<Result<Vec<U>, E>>()?.into_iter())
7    }
8
9    fn to_vec(self) -> Vec<Self::Item> {
10        self.collect()
11    }
12
13    fn try_to_vec<T, E>(self) -> Result<Vec<T>, E>
14    where
15        Self: Iterator<Item = Result<T, E>>,
16    {
17        self.collect()
18    }
19}
20
21impl<I: Iterator + Sized> IteratorExtensions for I {}
22
23pub trait IntoIteratorExtensions: Iterator + Sized {
24    fn join_to_string(self, sep: impl AsRef<str>) -> String
25    where
26        Self::Item: ToString,
27    {
28        self.into_iter()
29            .map(|t| t.to_string())
30            .to_vec()
31            .join(sep.as_ref())
32    }
33}
34
35impl<I: Iterator + Sized> IntoIteratorExtensions for I {}