1 use crate::iter::{FusedIterator, TrustedLen};
3 /// Creates an iterator that yields an element exactly once.
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.
10 /// [`chain()`]: Iterator::chain
19 /// // one is the loneliest number
20 /// let mut one = iter::once(1);
22 /// assert_eq!(Some(1), one.next());
24 /// // just one, that's all we get
25 /// assert_eq!(None, one.next());
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,
35 /// use std::path::PathBuf;
37 /// let dirs = fs::read_dir(".foo").unwrap();
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());
43 /// // now, our iterator just for our config file
44 /// let config = iter::once(PathBuf::from(".foorc"));
46 /// // chain the two iterators together into one big iterator
47 /// let files = dirs.chain(config);
49 /// // this will give us all of the files in .foo as well as .foorc
51 /// println!("{f:?}");
54 #[stable(feature = "iter_once", since = "1.2.0")]
55 pub fn once<T>(value: T) -> Once<T> {
56 Once { inner: Some(value).into_iter() }
59 /// An iterator that yields an element exactly once.
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")]
65 inner: crate::option::IntoIter<T>,
68 #[stable(feature = "iter_once", since = "1.2.0")]
69 impl<T> Iterator for Once<T> {
72 fn next(&mut self) -> Option<T> {
76 fn size_hint(&self) -> (usize, Option<usize>) {
77 self.inner.size_hint()
81 #[stable(feature = "iter_once", since = "1.2.0")]
82 impl<T> DoubleEndedIterator for Once<T> {
83 fn next_back(&mut self) -> Option<T> {
84 self.inner.next_back()
88 #[stable(feature = "iter_once", since = "1.2.0")]
89 impl<T> ExactSizeIterator for Once<T> {
90 fn len(&self) -> usize {
95 #[unstable(feature = "trusted_len", issue = "37572")]
96 unsafe impl<T> TrustedLen for Once<T> {}
98 #[stable(feature = "fused", since = "1.26.0")]
99 impl<T> FusedIterator for Once<T> {}