1 use crate::stream::{self, Iter, Stream};
2 
3 use core::option;
4 use core::pin::Pin;
5 use core::task::{Context, Poll};
6 
7 /// Stream for the [`once`](fn@once) function.
8 #[derive(Debug)]
9 #[must_use = "streams do nothing unless polled"]
10 pub struct Once<T> {
11     iter: Iter<option::IntoIter<T>>,
12 }
13 
14 impl<I> Unpin for Once<I> {}
15 
16 /// Creates a stream that emits an element exactly once.
17 ///
18 /// The returned stream is immediately ready and emits the provided value once.
19 ///
20 /// # Examples
21 ///
22 /// ```
23 /// use tokio::stream::{self, StreamExt};
24 ///
25 /// #[tokio::main]
26 /// async fn main() {
27 ///     // one is the loneliest number
28 ///     let mut one = stream::once(1);
29 ///
30 ///     assert_eq!(Some(1), one.next().await);
31 ///
32 ///     // just one, that's all we get
33 ///     assert_eq!(None, one.next().await);
34 /// }
35 /// ```
once<T>(value: T) -> Once<T>36 pub fn once<T>(value: T) -> Once<T> {
37     Once {
38         iter: stream::iter(Some(value).into_iter()),
39     }
40 }
41 
42 impl<T> Stream for Once<T> {
43     type Item = T;
44 
poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>>45     fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
46         Pin::new(&mut self.iter).poll_next(cx)
47     }
48 
size_hint(&self) -> (usize, Option<usize>)49     fn size_hint(&self) -> (usize, Option<usize>) {
50         self.iter.size_hint()
51     }
52 }
53