]> git.lizzy.rs Git - rust.git/blob - library/core/src/iter/adapters/skip.rs
Rollup merge of #79293 - Havvy:test-eval-order-compound-assign, r=Mark-Simulacrum
[rust.git] / library / core / src / iter / adapters / skip.rs
1 use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable};
2 use crate::ops::{ControlFlow, Try};
3
4 /// An iterator that skips over `n` elements of `iter`.
5 ///
6 /// This `struct` is created by the [`skip`] method on [`Iterator`]. See its
7 /// documentation for more.
8 ///
9 /// [`skip`]: Iterator::skip
10 /// [`Iterator`]: trait.Iterator.html
11 #[derive(Clone, Debug)]
12 #[must_use = "iterators are lazy and do nothing unless consumed"]
13 #[stable(feature = "rust1", since = "1.0.0")]
14 pub struct Skip<I> {
15     iter: I,
16     n: usize,
17 }
18
19 impl<I> Skip<I> {
20     pub(in crate::iter) fn new(iter: I, n: usize) -> Skip<I> {
21         Skip { iter, n }
22     }
23 }
24
25 #[stable(feature = "rust1", since = "1.0.0")]
26 impl<I> Iterator for Skip<I>
27 where
28     I: Iterator,
29 {
30     type Item = <I as Iterator>::Item;
31
32     #[inline]
33     fn next(&mut self) -> Option<I::Item> {
34         if self.n == 0 {
35             self.iter.next()
36         } else {
37             let old_n = self.n;
38             self.n = 0;
39             self.iter.nth(old_n)
40         }
41     }
42
43     #[inline]
44     fn nth(&mut self, n: usize) -> Option<I::Item> {
45         // Can't just add n + self.n due to overflow.
46         if self.n > 0 {
47             let to_skip = self.n;
48             self.n = 0;
49             // nth(n) skips n+1
50             self.iter.nth(to_skip - 1)?;
51         }
52         self.iter.nth(n)
53     }
54
55     #[inline]
56     fn count(mut self) -> usize {
57         if self.n > 0 {
58             // nth(n) skips n+1
59             if self.iter.nth(self.n - 1).is_none() {
60                 return 0;
61             }
62         }
63         self.iter.count()
64     }
65
66     #[inline]
67     fn last(mut self) -> Option<I::Item> {
68         if self.n > 0 {
69             // nth(n) skips n+1
70             self.iter.nth(self.n - 1)?;
71         }
72         self.iter.last()
73     }
74
75     #[inline]
76     fn size_hint(&self) -> (usize, Option<usize>) {
77         let (lower, upper) = self.iter.size_hint();
78
79         let lower = lower.saturating_sub(self.n);
80         let upper = match upper {
81             Some(x) => Some(x.saturating_sub(self.n)),
82             None => None,
83         };
84
85         (lower, upper)
86     }
87
88     #[inline]
89     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
90     where
91         Self: Sized,
92         Fold: FnMut(Acc, Self::Item) -> R,
93         R: Try<Ok = Acc>,
94     {
95         let n = self.n;
96         self.n = 0;
97         if n > 0 {
98             // nth(n) skips n+1
99             if self.iter.nth(n - 1).is_none() {
100                 return try { init };
101             }
102         }
103         self.iter.try_fold(init, fold)
104     }
105
106     #[inline]
107     fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
108     where
109         Fold: FnMut(Acc, Self::Item) -> Acc,
110     {
111         if self.n > 0 {
112             // nth(n) skips n+1
113             if self.iter.nth(self.n - 1).is_none() {
114                 return init;
115             }
116         }
117         self.iter.fold(init, fold)
118     }
119 }
120
121 #[stable(feature = "rust1", since = "1.0.0")]
122 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
123
124 #[stable(feature = "double_ended_skip_iterator", since = "1.9.0")]
125 impl<I> DoubleEndedIterator for Skip<I>
126 where
127     I: DoubleEndedIterator + ExactSizeIterator,
128 {
129     fn next_back(&mut self) -> Option<Self::Item> {
130         if self.len() > 0 { self.iter.next_back() } else { None }
131     }
132
133     #[inline]
134     fn nth_back(&mut self, n: usize) -> Option<I::Item> {
135         let len = self.len();
136         if n < len {
137             self.iter.nth_back(n)
138         } else {
139             if len > 0 {
140                 // consume the original iterator
141                 self.iter.nth_back(len - 1);
142             }
143             None
144         }
145     }
146
147     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
148     where
149         Self: Sized,
150         Fold: FnMut(Acc, Self::Item) -> R,
151         R: Try<Ok = Acc>,
152     {
153         fn check<T, Acc, R: Try<Ok = Acc>>(
154             mut n: usize,
155             mut fold: impl FnMut(Acc, T) -> R,
156         ) -> impl FnMut(Acc, T) -> ControlFlow<R, Acc> {
157             move |acc, x| {
158                 n -= 1;
159                 let r = fold(acc, x);
160                 if n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) }
161             }
162         }
163
164         let n = self.len();
165         if n == 0 { try { init } } else { self.iter.try_rfold(init, check(n, fold)).into_try() }
166     }
167
168     fn rfold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
169     where
170         Fold: FnMut(Acc, Self::Item) -> Acc,
171     {
172         #[inline]
173         fn ok<Acc, T>(mut f: impl FnMut(Acc, T) -> Acc) -> impl FnMut(Acc, T) -> Result<Acc, !> {
174             move |acc, x| Ok(f(acc, x))
175         }
176
177         self.try_rfold(init, ok(fold)).unwrap()
178     }
179 }
180
181 #[stable(feature = "fused", since = "1.26.0")]
182 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
183
184 #[unstable(issue = "none", feature = "inplace_iteration")]
185 unsafe impl<S: Iterator, I: Iterator> SourceIter for Skip<I>
186 where
187     I: SourceIter<Source = S>,
188 {
189     type Source = S;
190
191     #[inline]
192     unsafe fn as_inner(&mut self) -> &mut S {
193         // SAFETY: unsafe function forwarding to unsafe function with the same requirements
194         unsafe { SourceIter::as_inner(&mut self.iter) }
195     }
196 }
197
198 #[unstable(issue = "none", feature = "inplace_iteration")]
199 unsafe impl<I: InPlaceIterable> InPlaceIterable for Skip<I> {}