apollo_utils/
iterators.rs

1pub trait TryIntoElementwise<A, B: TryInto<A, Error = E>, E>: IntoIterator {
2    /// Performs try_into on each element of the iterator and collects the
3    /// results into a Vec.
4    fn try_into_elementwise(self) -> Result<Vec<A>, E>;
5}
6
7impl<A, B, E, I> TryIntoElementwise<A, B, E> for I
8where
9    B: TryInto<A, Error = E>,
10    I: IntoIterator<Item = B>,
11{
12    fn try_into_elementwise(self) -> Result<Vec<A>, E> {
13        self.into_iter()
14            .map(|x| x.try_into())
15            .collect::<Result<Vec<_>, E>>()
16    }
17}
18
19pub trait IntoElementwise<A, B: Into<A>>: IntoIterator {
20    /// Performs into on each element of the iterator and collects the
21    /// results into a Vec.
22    fn into_elementwise(self) -> Vec<A>;
23}
24
25impl<A, B, I> IntoElementwise<A, B> for I
26where
27    B: Into<A>,
28    I: IntoIterator<Item = B>,
29{
30    fn into_elementwise(self) -> Vec<A> {
31        self.into_iter().map(|x| x.into()).collect()
32    }
33}
34
35#[cfg(test)]
36mod tests {
37    use super::TryIntoElementwise;
38    use crate::iterators::IntoElementwise;
39    use std::num::TryFromIntError;
40    use test_case::test_case;
41
42    #[test_case(
43        vec![1u64, 2u64, 3u64] => Ok(vec![1u32, 2u32, 3u32]);
44        "Element wise OK")]
45    #[test_case(
46        vec![u64::MAX, 2u64, 3u64] => matches Err(_);
47            "Element wise Fail")]
48    fn test_try_into_elementwise(input: Vec<u64>) -> Result<Vec<u32>, TryFromIntError> {
49        // let result: Result<Vec<u32>, ParseError> =
50        input.into_iter().try_into_elementwise()
51    }
52
53    #[test_case(
54        vec![1u32, 2u32, 3u32] => vec![1u64, 2u64, 3u64];
55        "Element wise OK")]
56    fn test_into_elementwise(input: Vec<u32>) -> Vec<u64> {
57        input.into_elementwise()
58    }
59}