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").unwrap();
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/// ```
54#[stable(feature = "iter_once", since = "1.2.0")]
55pub fn once<T>(value: T) -> Once<T> {
56 Once { inner: Some(value).into_iter() }
57}
58
59/// An iterator that yields an element exactly once.
60///
61/// This `struct` is created by the [`once()`] function. See its documentation for more.
62#[derive(Clone, Debug)]
63#[stable(feature = "iter_once", since = "1.2.0")]
64#[rustc_diagnostic_item = "IterOnce"]
65pub struct Once<T> {
66 inner: crate::option::IntoIter<T>,
67}
68
69#[stable(feature = "iter_once", since = "1.2.0")]
70impl<T> Iterator for Once<T> {
71 type Item = T;
72
73 fn next(&mut self) -> Option<T> {
74 self.inner.next()
75 }
76
77 fn size_hint(&self) -> (usize, Option<usize>) {
78 self.inner.size_hint()
79 }
80}
81
82#[stable(feature = "iter_once", since = "1.2.0")]
83impl<T> DoubleEndedIterator for Once<T> {
84 fn next_back(&mut self) -> Option<T> {
85 self.inner.next_back()
86 }
87}
88
89#[stable(feature = "iter_once", since = "1.2.0")]
90impl<T> ExactSizeIterator for Once<T> {
91 fn len(&self) -> usize {
92 self.inner.len()
93 }
94}
95
96#[unstable(feature = "trusted_len", issue = "37572")]
97unsafe impl<T> TrustedLen for Once<T> {}
98
99#[stable(feature = "fused", since = "1.26.0")]
100impl<T> FusedIterator for Once<T> {}
101