-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathutils.rs
54 lines (50 loc) · 1.52 KB
/
utils.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/// If the first iterator is longer than the second, the zip implementation
/// in the standard library will still advance the the first iterator before
/// realizing that the second iterator has finished.
///
/// This implementation will advance the shorter iterator first avoiding
/// the issue above.
///
/// If you can guarantee that the first iterator is always shorter than the
/// second, you should use the zip impl in stdlib.
pub(crate) struct ZipWithProperAdvance<
A: ExactSizeIterator<Item = IA>,
B: ExactSizeIterator<Item = IB>,
IA,
IB,
> {
a: A,
b: B,
iter_a_first: bool,
}
impl<A: ExactSizeIterator<Item = IA>, B: ExactSizeIterator<Item = IB>, IA, IB>
ZipWithProperAdvance<A, B, IA, IB>
{
pub(crate) fn new(a: A, b: B) -> Self {
let iter_a_first = a.len() <= b.len();
Self { a, b, iter_a_first }
}
}
impl<A: ExactSizeIterator<Item = IA>, B: ExactSizeIterator<Item = IB>, IA, IB> Iterator
for ZipWithProperAdvance<A, B, IA, IB>
{
type Item = (IA, IB);
fn next(&mut self) -> Option<Self::Item> {
if self.iter_a_first {
let a = self.a.next()?;
let b = self.b.next()?;
Some((a, b))
} else {
let b = self.b.next()?;
let a = self.a.next()?;
Some((a, b))
}
}
}
impl<A: ExactSizeIterator<Item = IA>, B: ExactSizeIterator<Item = IB>, IA, IB> ExactSizeIterator
for ZipWithProperAdvance<A, B, IA, IB>
{
fn len(&self) -> usize {
self.a.len().min(self.b.len())
}
}