Skip to main content

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, consuming [`Self`].
37    pub fn into_peek(self) -> I::Item {
38        self.item
39    }
40
41    /// Returns the peeked item and the underlying iterator.
42    pub fn get(self) -> (I::Item, I) {
43        (self.item, self.rest)
44    }
45}
46
47impl<I: Iterator> IntoIterator for Peeked<I> {
48    type Item = I::Item;
49
50    type IntoIter = iter::Chain<iter::Once<I::Item>, I>;
51
52    fn into_iter(self) -> Self::IntoIter {
53        iter::once(self.item).chain(self.rest)
54    }
55}
56
57unsafe impl<I: Iterator> NonEmptyIterator for Peeked<I> {}