|
1 |
| -use crate::rule::NonEmptyRule; |
| 1 | +use crate::rule::{EmptyDefinition, NonEmptyRule}; |
2 | 2 | use crate::Refined;
|
| 3 | +use std::iter::Map; |
3 | 4 |
|
4 | 5 | use std::ops::Add;
|
| 6 | +use std::vec::IntoIter; |
| 7 | + |
| 8 | +impl<I: ExactSizeIterator + EmptyDefinition> Refined<NonEmptyRule<I>> { |
| 9 | + pub fn map<B, F>(self, f: F) -> Refined<NonEmptyRule<Map<I, F>>> |
| 10 | + where |
| 11 | + Self: Sized, |
| 12 | + F: FnMut(I::Item) -> B, |
| 13 | + { |
| 14 | + let map_into_iter = self.into_value().map(f); |
| 15 | + Refined::new(map_into_iter) |
| 16 | + .ok() |
| 17 | + .expect("This error is always unreachable") |
| 18 | + } |
| 19 | + |
| 20 | + pub fn collect<B: FromIterator<I::Item> + EmptyDefinition>(self) -> Refined<NonEmptyRule<B>> |
| 21 | + where |
| 22 | + Self: Sized, |
| 23 | + { |
| 24 | + let a: B = FromIterator::from_iter(self.into_value()); |
| 25 | + Refined::new(a).ok().expect("") |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +pub type NonEmptyIntoIter<T> = Refined<NonEmptyIntoIterRule<T>>; |
| 30 | +pub type NonEmptyIntoIterRule<T> = NonEmptyRule<IntoIter<T>>; |
| 31 | + |
| 32 | +pub type NonEmptyMap<I, F> = Refined<NonEmptyMapRule<I, F>>; |
| 33 | +pub type NonEmptyMapRule<I, F> = NonEmptyRule<Map<I, F>>; |
| 34 | + |
| 35 | +// impl<T> NonEmptyIntoIter<T> { |
| 36 | +// pub fn map<B, F>(self, f: F) -> Refined<NonEmptyRule<Map<IntoIter<T>, F>>> |
| 37 | +// where |
| 38 | +// Self: Sized, |
| 39 | +// F: FnMut(T) -> B, |
| 40 | +// { |
| 41 | +// let map_into_iter = self.into_value().map(f); |
| 42 | +// Refined::new(map_into_iter) |
| 43 | +// .ok() |
| 44 | +// .expect("This error is always unreachable") |
| 45 | +// } |
| 46 | +// } |
5 | 47 |
|
6 | 48 | pub type NonEmptyVec<T> = Refined<NonEmptyVecRule<T>>;
|
7 | 49 |
|
| 50 | +impl<T> NonEmptyVec<T> |
| 51 | +where |
| 52 | + T: EmptyDefinition, |
| 53 | +{ |
| 54 | + #[allow(clippy::should_implement_trait)] |
| 55 | + pub fn into_iter(self) -> NonEmptyIntoIter<T> { |
| 56 | + Refined::new(self.into_value().into_iter()) |
| 57 | + .ok() |
| 58 | + .expect("This error is always unreachable") |
| 59 | + } |
| 60 | +} |
| 61 | + |
8 | 62 | impl<T> Add for NonEmptyVec<T> {
|
9 | 63 | type Output = Self;
|
10 | 64 |
|
@@ -38,4 +92,16 @@ mod test {
|
38 | 92 | assert_eq!(ne_vec.into_value(), vec![1, 2, 3, 4, 5, 6]);
|
39 | 93 | Ok(())
|
40 | 94 | }
|
| 95 | + |
| 96 | + #[test] |
| 97 | + fn test_into_iter() -> anyhow::Result<()> { |
| 98 | + let ne_vec = NonEmptyVec::new(vec![1, 2, 3])?; |
| 99 | + let ne_vec = ne_vec |
| 100 | + .into_iter() |
| 101 | + .map(|n| n * 2) |
| 102 | + .map(|n| n * 3) |
| 103 | + .collect::<Vec<_>>(); |
| 104 | + assert_eq!(ne_vec.into_value(), vec![6, 12, 18]); |
| 105 | + Ok(()) |
| 106 | + } |
41 | 107 | }
|
0 commit comments