1use crate::size_hint;
2use crate::PeekingNext;
3use alloc::collections::VecDeque;
4use std::iter::Fuse;
5
6/// See [`peek_nth()`] for more information.
7#[derive(Clone, Debug)]
8pub struct PeekNth<I>
9where
10 I: Iterator,
11{
12 iter: Fuse<I>,
13 buf: VecDeque<I::Item>,
14}
15
16/// A drop-in replacement for [`std::iter::Peekable`] which adds a `peek_nth`
17/// method allowing the user to `peek` at a value several iterations forward
18/// without advancing the base iterator.
19///
20/// This differs from `multipeek` in that subsequent calls to `peek` or
21/// `peek_nth` will always return the same value until `next` is called
22/// (making `reset_peek` unnecessary).
23pub fn peek_nth<I>(iterable: I) -> PeekNth<I::IntoIter>
24where
25 I: IntoIterator,
26{
27 PeekNth {
28 iter: iterable.into_iter().fuse(),
29 buf: VecDeque::new(),
30 }
31}
32
33impl<I> PeekNth<I>
34where
35 I: Iterator,
36{
37 /// Works exactly like the `peek` method in `std::iter::Peekable`
38 pub fn peek(&mut self) -> Option<&I::Item> {
39 self.peek_nth(0)
40 }
41
42 /// Returns a reference to the `nth` value without advancing the iterator.
43 ///
44 /// # Examples
45 ///
46 /// Basic usage:
47 ///
48 /// ```rust
49 /// use itertools::peek_nth;
50 ///
51 /// let xs = vec![1,2,3];
52 /// let mut iter = peek_nth(xs.iter());
53 ///
54 /// assert_eq!(iter.peek_nth(0), Some(&&1));
55 /// assert_eq!(iter.next(), Some(&1));
56 ///
57 /// // The iterator does not advance even if we call `peek_nth` multiple times
58 /// assert_eq!(iter.peek_nth(0), Some(&&2));
59 /// assert_eq!(iter.peek_nth(1), Some(&&3));
60 /// assert_eq!(iter.next(), Some(&2));
61 ///
62 /// // Calling `peek_nth` past the end of the iterator will return `None`
63 /// assert_eq!(iter.peek_nth(1), None);
64 /// ```
65 pub fn peek_nth(&mut self, n: usize) -> Option<&I::Item> {
66 let unbuffered_items = (n + 1).saturating_sub(self.buf.len());
67
68 self.buf.extend(self.iter.by_ref().take(unbuffered_items));
69
70 self.buf.get(n)
71 }
72}
73
74impl<I> Iterator for PeekNth<I>
75where
76 I: Iterator,
77{
78 type Item = I::Item;
79
80 fn next(&mut self) -> Option<Self::Item> {
81 self.buf.pop_front().or_else(|| self.iter.next())
82 }
83
84 fn size_hint(&self) -> (usize, Option<usize>) {
85 size_hint::add_scalar(self.iter.size_hint(), self.buf.len())
86 }
87}
88
89impl<I> ExactSizeIterator for PeekNth<I> where I: ExactSizeIterator {}
90
91impl<I> PeekingNext for PeekNth<I>
92where
93 I: Iterator,
94{
95 fn peeking_next<F>(&mut self, accept: F) -> Option<Self::Item>
96 where
97 F: FnOnce(&Self::Item) -> bool,
98 {
99 self.peek().filter(|item| accept(item))?;
100 self.next()
101 }
102}
103