1 use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedLen};
4 /// An iterator with a `peek()` that returns an optional reference to the next
7 /// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
8 /// documentation for more.
10 /// [`peekable`]: Iterator::peekable
11 /// [`Iterator`]: trait.Iterator.html
12 #[derive(Clone, Debug)]
13 #[must_use = "iterators are lazy and do nothing unless consumed"]
14 #[stable(feature = "rust1", since = "1.0.0")]
15 pub struct Peekable<I: Iterator> {
17 /// Remember a peeked value, even if it was None.
18 peeked: Option<Option<I::Item>>,
21 impl<I: Iterator> Peekable<I> {
22 pub(in crate::iter) fn new(iter: I) -> Peekable<I> {
23 Peekable { iter, peeked: None }
27 // Peekable must remember if a None has been seen in the `.peek()` method.
28 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
29 // underlying iterator at most once. This does not by itself make the iterator
31 #[stable(feature = "rust1", since = "1.0.0")]
32 impl<I: Iterator> Iterator for Peekable<I> {
36 fn next(&mut self) -> Option<I::Item> {
37 match self.peeked.take() {
39 None => self.iter.next(),
44 #[rustc_inherit_overflow_checks]
45 fn count(mut self) -> usize {
46 match self.peeked.take() {
48 Some(Some(_)) => 1 + self.iter.count(),
49 None => self.iter.count(),
54 fn nth(&mut self, n: usize) -> Option<I::Item> {
55 match self.peeked.take() {
57 Some(v @ Some(_)) if n == 0 => v,
58 Some(Some(_)) => self.iter.nth(n - 1),
59 None => self.iter.nth(n),
64 fn last(mut self) -> Option<I::Item> {
65 let peek_opt = match self.peeked.take() {
66 Some(None) => return None,
70 self.iter.last().or(peek_opt)
74 fn size_hint(&self) -> (usize, Option<usize>) {
75 let peek_len = match self.peeked {
76 Some(None) => return (0, Some(0)),
80 let (lo, hi) = self.iter.size_hint();
81 let lo = lo.saturating_add(peek_len);
83 Some(x) => x.checked_add(peek_len),
90 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
93 F: FnMut(B, Self::Item) -> R,
96 let acc = match self.peeked.take() {
97 Some(None) => return try { init },
98 Some(Some(v)) => f(init, v)?,
101 self.iter.try_fold(acc, f)
105 fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
107 Fold: FnMut(Acc, Self::Item) -> Acc,
109 let acc = match self.peeked {
110 Some(None) => return init,
111 Some(Some(v)) => fold(init, v),
114 self.iter.fold(acc, fold)
118 #[stable(feature = "double_ended_peek_iterator", since = "1.38.0")]
119 impl<I> DoubleEndedIterator for Peekable<I>
121 I: DoubleEndedIterator,
124 fn next_back(&mut self) -> Option<Self::Item> {
125 match self.peeked.as_mut() {
126 Some(v @ Some(_)) => self.iter.next_back().or_else(|| v.take()),
128 None => self.iter.next_back(),
133 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
136 F: FnMut(B, Self::Item) -> R,
139 match self.peeked.take() {
140 Some(None) => try { init },
141 Some(Some(v)) => match self.iter.try_rfold(init, &mut f).into_result() {
142 Ok(acc) => f(acc, v),
144 self.peeked = Some(Some(v));
148 None => self.iter.try_rfold(init, f),
153 fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
155 Fold: FnMut(Acc, Self::Item) -> Acc,
160 let acc = self.iter.rfold(init, &mut fold);
163 None => self.iter.rfold(init, fold),
168 #[stable(feature = "rust1", since = "1.0.0")]
169 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
171 #[stable(feature = "fused", since = "1.26.0")]
172 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
174 impl<I: Iterator> Peekable<I> {
175 /// Returns a reference to the next() value without advancing the iterator.
177 /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
178 /// But if the iteration is over, `None` is returned.
180 /// [`next`]: Iterator::next
182 /// Because `peek()` returns a reference, and many iterators iterate over
183 /// references, there can be a possibly confusing situation where the
184 /// return value is a double reference. You can see this effect in the
192 /// let xs = [1, 2, 3];
194 /// let mut iter = xs.iter().peekable();
196 /// // peek() lets us see into the future
197 /// assert_eq!(iter.peek(), Some(&&1));
198 /// assert_eq!(iter.next(), Some(&1));
200 /// assert_eq!(iter.next(), Some(&2));
202 /// // The iterator does not advance even if we `peek` multiple times
203 /// assert_eq!(iter.peek(), Some(&&3));
204 /// assert_eq!(iter.peek(), Some(&&3));
206 /// assert_eq!(iter.next(), Some(&3));
208 /// // After the iterator is finished, so is `peek()`
209 /// assert_eq!(iter.peek(), None);
210 /// assert_eq!(iter.next(), None);
213 #[stable(feature = "rust1", since = "1.0.0")]
214 pub fn peek(&mut self) -> Option<&I::Item> {
215 let iter = &mut self.iter;
216 self.peeked.get_or_insert_with(|| iter.next()).as_ref()
219 /// Returns a mutable reference to the next() value without advancing the iterator.
221 /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
222 /// But if the iteration is over, `None` is returned.
224 /// Because `peek_mut()` returns a reference, and many iterators iterate over
225 /// references, there can be a possibly confusing situation where the
226 /// return value is a double reference. You can see this effect in the examples
229 /// [`next`]: Iterator::next
236 /// #![feature(peekable_peek_mut)]
237 /// let mut iter = [1, 2, 3].iter().peekable();
239 /// // Like with `peek()`, we can see into the future without advancing the iterator.
240 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
241 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
242 /// assert_eq!(iter.next(), Some(&1));
244 /// // Peek into the iterator and set the value behind the mutable reference.
245 /// if let Some(p) = iter.peek_mut() {
246 /// assert_eq!(*p, &2);
250 /// // The value we put in reappears as the iterator continues.
251 /// assert_eq!(iter.collect::<Vec<_>>(), vec![&5, &3]);
254 #[unstable(feature = "peekable_peek_mut", issue = "78302")]
255 pub fn peek_mut(&mut self) -> Option<&mut I::Item> {
256 let iter = &mut self.iter;
257 self.peeked.get_or_insert_with(|| iter.next()).as_mut()
260 /// Consume and return the next value of this iterator if a condition is true.
262 /// If `func` returns `true` for the next value of this iterator, consume and return it.
263 /// Otherwise, return `None`.
266 /// Consume a number if it's equal to 0.
268 /// #![feature(peekable_next_if)]
269 /// let mut iter = (0..5).peekable();
270 /// // The first item of the iterator is 0; consume it.
271 /// assert_eq!(iter.next_if(|&x| x == 0), Some(0));
272 /// // The next item returned is now 1, so `consume` will return `false`.
273 /// assert_eq!(iter.next_if(|&x| x == 0), None);
274 /// // `next_if` saves the value of the next item if it was not equal to `expected`.
275 /// assert_eq!(iter.next(), Some(1));
278 /// Consume any number less than 10.
280 /// #![feature(peekable_next_if)]
281 /// let mut iter = (1..20).peekable();
282 /// // Consume all numbers less than 10
283 /// while iter.next_if(|&x| x < 10).is_some() {}
284 /// // The next value returned will be 10
285 /// assert_eq!(iter.next(), Some(10));
287 #[unstable(feature = "peekable_next_if", issue = "72480")]
288 pub fn next_if(&mut self, func: impl FnOnce(&I::Item) -> bool) -> Option<I::Item> {
290 Some(matched) if func(&matched) => Some(matched),
292 // Since we called `self.next()`, we consumed `self.peeked`.
293 assert!(self.peeked.is_none());
294 self.peeked = Some(other);
300 /// Consume and return the next item if it is equal to `expected`.
303 /// Consume a number if it's equal to 0.
305 /// #![feature(peekable_next_if)]
306 /// let mut iter = (0..5).peekable();
307 /// // The first item of the iterator is 0; consume it.
308 /// assert_eq!(iter.next_if_eq(&0), Some(0));
309 /// // The next item returned is now 1, so `consume` will return `false`.
310 /// assert_eq!(iter.next_if_eq(&0), None);
311 /// // `next_if_eq` saves the value of the next item if it was not equal to `expected`.
312 /// assert_eq!(iter.next(), Some(1));
314 #[unstable(feature = "peekable_next_if", issue = "72480")]
315 pub fn next_if_eq<T>(&mut self, expected: &T) -> Option<I::Item>
318 I::Item: PartialEq<T>,
320 self.next_if(|next| next == expected)
324 #[unstable(feature = "trusted_len", issue = "37572")]
325 unsafe impl<I> TrustedLen for Peekable<I> where I: TrustedLen {}
327 #[unstable(issue = "none", feature = "inplace_iteration")]
328 unsafe impl<S: Iterator, I: Iterator> SourceIter for Peekable<I>
330 I: SourceIter<Source = S>,
335 unsafe fn as_inner(&mut self) -> &mut S {
336 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
337 unsafe { SourceIter::as_inner(&mut self.iter) }
341 #[unstable(issue = "none", feature = "inplace_iteration")]
342 unsafe impl<I: InPlaceIterable> InPlaceIterable for Peekable<I> {}