core/iter/sources/once.rs
1use crate::iter::{FusedIterator, TrustedLen};
2
3/// Creates an iterator that yields an element exactly once.
4///
5/// This is commonly used to adapt a single value into a [`chain()`] of other
6/// kinds of iteration. Maybe you have an iterator that covers almost
7/// everything, but you need an extra special case. Maybe you have a function
8/// which works on iterators, but you only need to process one value.
9///
10/// [`chain()`]: Iterator::chain
11///
12/// # Examples
13///
14/// Basic usage:
15///
16/// ```
17/// use std::iter;
18///
19/// // one is the loneliest number
20/// let mut one = iter::once(1);
21///
22/// assert_eq!(Some(1), one.next());
23///
24/// // just one, that's all we get
25/// assert_eq!(None, one.next());
26/// ```
27///
28/// Chaining together with another iterator. Let's say that we want to iterate
29/// over each file of the `.foo` directory, but also a configuration file,
30/// `.foorc`:
31///
32/// ```no_run
33/// use std::iter;
34/// use std::fs;
35/// use std::path::PathBuf;
36///
37/// let dirs = fs::read_dir(".foo")?;
38///
39/// // we need to convert from an iterator of DirEntry-s to an iterator of
40/// // PathBufs, so we use map
41/// let dirs = dirs.map(|file| file.unwrap().path());
42///
43/// // now, our iterator just for our config file
44/// let config = iter::once(PathBuf::from(".foorc"));
45///
46/// // chain the two iterators together into one big iterator
47/// let files = dirs.chain(config);
48///
49/// // this will give us all of the files in .foo as well as .foorc
50/// for f in files {
51/// println!("{f:?}");
52/// }
53/// # std::io::Result::Ok(())
54/// ```
55#[stable(feature = "iter_once", since = "1.2.0")]
56pub fn once<T>(value: T) -> Once<T> {
57 Once { inner: Some(value).into_iter() }
58}
59
60/// An iterator that yields an element exactly once.
61///
62/// This `struct` is created by the [`once()`] function. See its documentation for more.
63#[derive(Clone, Debug)]
64#[stable(feature = "iter_once", since = "1.2.0")]
65#[rustc_diagnostic_item = "IterOnce"]
66pub struct Once<T> {
67 inner: crate::option::IntoIter<T>,
68}
69
70#[stable(feature = "iter_once", since = "1.2.0")]
71impl<T> Iterator for Once<T> {
72 type Item = T;
73
74 fn next(&mut self) -> Option<T> {
75 self.inner.next()
76 }
77
78 fn size_hint(&self) -> (usize, Option<usize>) {
79 self.inner.size_hint()
80 }
81}
82
83#[stable(feature = "iter_once", since = "1.2.0")]
84impl<T> DoubleEndedIterator for Once<T> {
85 fn next_back(&mut self) -> Option<T> {
86 self.inner.next_back()
87 }
88}
89
90#[stable(feature = "iter_once", since = "1.2.0")]
91impl<T> ExactSizeIterator for Once<T> {
92 fn len(&self) -> usize {
93 self.inner.len()
94 }
95}
96
97#[unstable(feature = "trusted_len", issue = "37572")]
98unsafe impl<T> TrustedLen for Once<T> {}
99
100#[stable(feature = "fused", since = "1.26.0")]
101impl<T> FusedIterator for Once<T> {}