non_empty_iter/
peeked.rs

1//! Non-empty peeked iterators.
2
3use core::iter;
4
5use crate::non_empty::NonEmptyIterator;
6
7/// Represents non-empty peeked iterators.
8///
9/// This `struct` is created by the [`peeked`] method on [`NonEmptyIterator`].
10/// See its documentation for more.
11///
12/// [`peeked`]: NonEmptyIterator::peeked
13#[derive(Debug, Clone)]
14#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
15pub struct Peeked<I: Iterator> {
16    item: I::Item,
17    rest: I,
18}
19
20impl<I: Iterator> Peeked<I> {
21    /// Constructs [`Self`].
22    pub const fn new(item: I::Item, rest: I) -> Self {
23        Self { item, rest }
24    }
25
26    /// Returns the immutable reference to the peeked item.
27    pub const fn peek(&self) -> &I::Item {
28        &self.item
29    }
30
31    /// Returns the mutable reference to the peeked item.
32    pub const fn peek_mut(&mut self) -> &mut I::Item {
33        &mut self.item
34    }
35
36    /// Returns the peeked item and the underlying iterator.
37    pub fn get(self) -> (I::Item, I) {
38        (self.item, self.rest)
39    }
40}
41
42impl<I: Iterator> IntoIterator for Peeked<I> {
43    type Item = I::Item;
44
45    type IntoIter = iter::Chain<iter::Once<I::Item>, I>;
46
47    fn into_iter(self) -> Self::IntoIter {
48        iter::once(self.item).chain(self.rest)
49    }
50}
51
52unsafe impl<I: Iterator> NonEmptyIterator for Peeked<I> {}