tokio_stream/
once.rs

1use crate::{Iter, Stream};
2
3use core::option;
4use core::pin::Pin;
5use core::task::{Context, Poll};
6
7/// Stream for the [`once`](fn@once) function.
8#[derive(Debug)]
9#[must_use = "streams do nothing unless polled"]
10pub struct Once<T> {
11    iter: Iter<option::IntoIter<T>>,
12}
13
14impl<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 as stream, 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/// ```
36pub fn once<T>(value: T) -> Once<T> {
37    Once {
38        iter: crate::iter(Some(value)),
39    }
40}
41
42impl<T> Stream for Once<T> {
43    type Item = T;
44
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
49    fn size_hint(&self) -> (usize, Option<usize>) {
50        self.iter.size_hint()
51    }
52}