Debian Codegraph @

debian/rust-vendor/itertools/tests/zip.rs

raw
1 use itertools::multizip;
2 use itertools::EitherOrBoth::{Both, Left, Right};
3 use itertools::Itertools;
4
5 #[test]
6 fn zip_longest_fused() {
7 let a = [Some(1), None, Some(3), Some(4)];
8 let b = [1, 2, 3];
9
10 let unfused = a
11 .iter()
12 .batching(|it| *it.next().unwrap())
13 .zip_longest(b.iter().cloned());
14 itertools::assert_equal(unfused, vec![Both(1, 1), Right(2), Right(3)]);
15 }
16
17 #[test]
18 fn test_zip_longest_size_hint() {
19 let c = (1..10).cycle();
20 let v: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
21 let v2 = &[10, 11, 12];
22
23 assert_eq!(c.zip_longest(v.iter()).size_hint(), (usize::MAX, None));
24
25 assert_eq!(v.iter().zip_longest(v2.iter()).size_hint(), (10, Some(10)));
26 }
27
28 #[test]
29 fn test_double_ended_zip_longest() {
30 let xs = [1, 2, 3, 4, 5, 6];
31 let ys = [1, 2, 3, 7];
32 let a = xs.iter().copied();
33 let b = ys.iter().copied();
34 let mut it = a.zip_longest(b);
35 assert_eq!(it.next(), Some(Both(1, 1)));
36 assert_eq!(it.next(), Some(Both(2, 2)));
37 assert_eq!(it.next_back(), Some(Left(6)));
38 assert_eq!(it.next_back(), Some(Left(5)));
39 assert_eq!(it.next_back(), Some(Both(4, 7)));
40 assert_eq!(it.next(), Some(Both(3, 3)));
41 assert_eq!(it.next(), None);
42 }
43
44 #[test]
45 fn test_double_ended_zip() {
46 let xs = [1, 2, 3, 4, 5, 6];
47 let ys = [1, 2, 3, 7];
48 let a = xs.iter().copied();
49 let b = ys.iter().copied();
50 let mut it = multizip((a, b));
51 assert_eq!(it.next_back(), Some((4, 7)));
52 assert_eq!(it.next_back(), Some((3, 3)));
53 assert_eq!(it.next_back(), Some((2, 2)));
54 assert_eq!(it.next_back(), Some((1, 1)));
55 assert_eq!(it.next_back(), None);
56 }
57
58 #[test]
59 /// The purpose of this test is not really to test the iterator mechanics itself, rather that it
60 /// compiles and accepts temporary values as inputs, as those would be valid when not used with the
61 /// izip! macro and zipped manually via .zip calls
62 fn test_izip_with_temporaries() {
63 struct Owned {
64 data: Vec<i32>,
65 }
66
67 impl Owned {
68 fn new(val: i32) -> Self {
69 Self {
70 data: vec![val; 10],
71 }
72 }
73
74 fn as_view(&self) -> View<'_> {
75 View {
76 data: self.data.as_slice(),
77 }
78 }
79 }
80
81 struct View<'a> {
82 data: &'a [i32],
83 }
84
85 impl View<'_> {
86 fn iter(&self) -> impl Iterator<Item = &i32> {
87 self.data.iter()
88 }
89 }
90
91 let a = Owned::new(0);
92 let b = Owned::new(1);
93 let c = Owned::new(2);
94
95 let mut sum = 0;
96
97 for (x, y, z) in itertools::izip!(a.as_view().iter(), b.as_view().iter(), c.as_view().iter()) {
98 sum += x + y + z;
99 }
100
101 assert_eq!(sum, 30);
102 }