]> git.proxmox.com Git - rustc.git/blob - vendor/itertools/src/pad_tail.rs
New upstream version 1.76.0+dfsg1
[rustc.git] / vendor / itertools / src / pad_tail.rs
1 use crate::size_hint;
2 use std::iter::{Fuse, FusedIterator};
3
4 /// An iterator adaptor that pads a sequence to a minimum length by filling
5 /// missing elements using a closure.
6 ///
7 /// Iterator element type is `I::Item`.
8 ///
9 /// See [`.pad_using()`](crate::Itertools::pad_using) for more information.
10 #[derive(Clone)]
11 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
12 pub struct PadUsing<I, F> {
13 iter: Fuse<I>,
14 min: usize,
15 pos: usize,
16 filler: F,
17 }
18
19 impl<I, F> std::fmt::Debug for PadUsing<I, F>
20 where
21 I: std::fmt::Debug,
22 {
23 debug_fmt_fields!(PadUsing, iter, min, pos);
24 }
25
26 /// Create a new `PadUsing` iterator.
27 pub fn pad_using<I, F>(iter: I, min: usize, filler: F) -> PadUsing<I, F>
28 where
29 I: Iterator,
30 F: FnMut(usize) -> I::Item,
31 {
32 PadUsing {
33 iter: iter.fuse(),
34 min,
35 pos: 0,
36 filler,
37 }
38 }
39
40 impl<I, F> Iterator for PadUsing<I, F>
41 where
42 I: Iterator,
43 F: FnMut(usize) -> I::Item,
44 {
45 type Item = I::Item;
46
47 #[inline]
48 fn next(&mut self) -> Option<Self::Item> {
49 match self.iter.next() {
50 None => {
51 if self.pos < self.min {
52 let e = Some((self.filler)(self.pos));
53 self.pos += 1;
54 e
55 } else {
56 None
57 }
58 }
59 e => {
60 self.pos += 1;
61 e
62 }
63 }
64 }
65
66 fn size_hint(&self) -> (usize, Option<usize>) {
67 let tail = self.min.saturating_sub(self.pos);
68 size_hint::max(self.iter.size_hint(), (tail, Some(tail)))
69 }
70 }
71
72 impl<I, F> DoubleEndedIterator for PadUsing<I, F>
73 where
74 I: DoubleEndedIterator + ExactSizeIterator,
75 F: FnMut(usize) -> I::Item,
76 {
77 fn next_back(&mut self) -> Option<Self::Item> {
78 if self.min == 0 {
79 self.iter.next_back()
80 } else if self.iter.len() >= self.min {
81 self.min -= 1;
82 self.iter.next_back()
83 } else {
84 self.min -= 1;
85 Some((self.filler)(self.min))
86 }
87 }
88 }
89
90 impl<I, F> ExactSizeIterator for PadUsing<I, F>
91 where
92 I: ExactSizeIterator,
93 F: FnMut(usize) -> I::Item,
94 {
95 }
96
97 impl<I, F> FusedIterator for PadUsing<I, F>
98 where
99 I: FusedIterator,
100 F: FnMut(usize) -> I::Item,
101 {
102 }