| 1 | use core::pin::Pin; |
| 2 | |
| 3 | use pin_project_lite::pin_project; |
| 4 | |
| 5 | use crate::stream::Stream; |
| 6 | use crate::task::{Context, Poll}; |
| 7 | |
| 8 | #[cfg (feature = "unstable" )] |
| 9 | use crate::stream::DoubleEndedStream; |
| 10 | |
| 11 | /// Creates a stream that yields a single item. |
| 12 | /// |
| 13 | /// # Examples |
| 14 | /// |
| 15 | /// ``` |
| 16 | /// # async_std::task::block_on(async { |
| 17 | /// # |
| 18 | /// use async_std::prelude::*; |
| 19 | /// use async_std::stream; |
| 20 | /// |
| 21 | /// let mut s = stream::once(7); |
| 22 | /// |
| 23 | /// assert_eq!(s.next().await, Some(7)); |
| 24 | /// assert_eq!(s.next().await, None); |
| 25 | /// # |
| 26 | /// # }) |
| 27 | /// ``` |
| 28 | pub fn once<T>(t: T) -> Once<T> { |
| 29 | Once { value: Some(t) } |
| 30 | } |
| 31 | |
| 32 | pin_project! { |
| 33 | /// A stream that yields a single item. |
| 34 | /// |
| 35 | /// This stream is created by the [`once`] function. See its |
| 36 | /// documentation for more. |
| 37 | /// |
| 38 | /// [`once`]: fn.once.html |
| 39 | #[derive (Clone, Debug)] |
| 40 | pub struct Once<T> { |
| 41 | value: Option<T>, |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | impl<T> Stream for Once<T> { |
| 46 | type Item = T; |
| 47 | |
| 48 | fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<T>> { |
| 49 | Poll::Ready(self.project().value.take()) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | #[cfg (feature = "unstable" )] |
| 54 | impl <T> DoubleEndedStream for Once<T> { |
| 55 | fn poll_next_back(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 56 | Poll::Ready(self.project().value.take()) |
| 57 | } |
| 58 | } |
| 59 | |