non_empty_iter/
once.rs

1//! Yielding items exactly once.
2
3use core::iter;
4
5use crate::non_empty::NonEmptyIterator;
6
7/// Creates [`Once<T>`], non-empty iterator that yields the given value exactly once.
8pub const fn once<T>(value: T) -> Once<T> {
9    Once::new(value)
10}
11
12/// Creates [`OnceWith<T>`] non-empty iterator that yields the value
13/// computed from the given function exactly once.
14pub const fn once_with<T, F: FnOnce() -> T>(function: F) -> OnceWith<F> {
15    OnceWith::new(function)
16}
17
18/// Represents non-empty iterators that yield the given value exactly once.
19///
20/// This `struct` is created by the [`once`] function. See its documentation for more.
21#[derive(Debug, Clone)]
22#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
23pub struct Once<T> {
24    value: T,
25}
26
27impl<T> Once<T> {
28    /// Constructs [`Self`].
29    pub const fn new(value: T) -> Self {
30        Self { value }
31    }
32}
33
34impl<T> IntoIterator for Once<T> {
35    type Item = T;
36
37    type IntoIter = iter::Once<T>;
38
39    fn into_iter(self) -> Self::IntoIter {
40        iter::once(self.value)
41    }
42}
43
44unsafe impl<T> NonEmptyIterator for Once<T> {}
45
46/// Represents non-empty iterators that yield the value computed from
47/// the given function exactly once.
48///
49/// This `struct` is created by the [`once_with`] function. See its documentation for more.
50#[derive(Debug, Clone)]
51#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
52pub struct OnceWith<F> {
53    function: F,
54}
55
56impl<F> OnceWith<F> {
57    /// Constructs [`Self`].
58    pub const fn new(function: F) -> Self {
59        Self { function }
60    }
61}
62
63impl<T, F: FnOnce() -> T> IntoIterator for OnceWith<F> {
64    type Item = T;
65
66    type IntoIter = iter::OnceWith<F>;
67
68    fn into_iter(self) -> Self::IntoIter {
69        iter::once_with(self.function)
70    }
71}
72
73unsafe impl<T, F: FnOnce() -> T> NonEmptyIterator for OnceWith<F> {}