]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/collections/vec_deque/pair_slices.rs
Auto merge of #84560 - cjgillot:inline-iter, r=m-ou-se
[rust.git] / library / alloc / src / collections / vec_deque / pair_slices.rs
1 use core::cmp::{self};
2 use core::mem::replace;
3
4 use super::VecDeque;
5
6 /// PairSlices pairs up equal length slice parts of two deques
7 ///
8 /// For example, given deques "A" and "B" with the following division into slices:
9 ///
10 /// A: [0 1 2] [3 4 5]
11 /// B: [a b] [c d e]
12 ///
13 /// It produces the following sequence of matching slices:
14 ///
15 /// ([0 1], [a b])
16 /// (\[2\], \[c\])
17 /// ([3 4], [d e])
18 ///
19 /// and the uneven remainder of either A or B is skipped.
20 pub struct PairSlices<'a, 'b, T> {
21     pub(crate) a0: &'a mut [T],
22     pub(crate) a1: &'a mut [T],
23     pub(crate) b0: &'b [T],
24     pub(crate) b1: &'b [T],
25 }
26
27 impl<'a, 'b, T> PairSlices<'a, 'b, T> {
28     pub fn from(to: &'a mut VecDeque<T>, from: &'b VecDeque<T>) -> Self {
29         let (a0, a1) = to.as_mut_slices();
30         let (b0, b1) = from.as_slices();
31         PairSlices { a0, a1, b0, b1 }
32     }
33
34     pub fn has_remainder(&self) -> bool {
35         !self.b0.is_empty()
36     }
37
38     pub fn remainder(self) -> impl Iterator<Item = &'b [T]> {
39         IntoIterator::into_iter([self.b0, self.b1])
40     }
41 }
42
43 impl<'a, 'b, T> Iterator for PairSlices<'a, 'b, T> {
44     type Item = (&'a mut [T], &'b [T]);
45     fn next(&mut self) -> Option<Self::Item> {
46         // Get next part length
47         let part = cmp::min(self.a0.len(), self.b0.len());
48         if part == 0 {
49             return None;
50         }
51         let (p0, p1) = replace(&mut self.a0, &mut []).split_at_mut(part);
52         let (q0, q1) = self.b0.split_at(part);
53
54         // Move a1 into a0, if it's empty (and b1, b0 the same way).
55         self.a0 = p1;
56         self.b0 = q1;
57         if self.a0.is_empty() {
58             self.a0 = replace(&mut self.a1, &mut []);
59         }
60         if self.b0.is_empty() {
61             self.b0 = replace(&mut self.b1, &[]);
62         }
63         Some((p0, q0))
64     }
65 }