From 1b1eb8a8de55ce24d677c8bcee0c6d0c11d8a786 Mon Sep 17 00:00:00 2001 From: Roman Proskuryakov Date: Thu, 10 Oct 2019 02:04:27 +0300 Subject: [PATCH] Implement stream::once --- README.md | 1 + src/stream.rs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/README.md b/README.md index 950fdca..79deb37 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ Stream - [x] stream::iter - [x] stream::map - [x] stream::next +- [x] stream::once - [x] stream::poll_fn - [x] stream::repeat - [x] stream::skip diff --git a/src/stream.rs b/src/stream.rs index 9fa7bb6..6c21249 100644 --- a/src/stream.rs +++ b/src/stream.rs @@ -38,6 +38,29 @@ where poll_fn(move |context| Pin::new(&mut stream).poll_next(context)) } +/// Creates a stream of a single element. +/// +/// ``` +/// # futures::executor::block_on(async { +/// use futures_async_combinators::stream::{once, collect}; +/// +/// let stream = once(async { 17 }); +/// let collection: Vec = collect(stream).await; +/// assert_eq!(collection, vec![17]); +/// # }); +/// ``` +pub fn once(future: F) -> impl Stream +where + F: Future, +{ + crate::stream::unfold(Some(future), |f| async move { + match f { + Some(f) => Some((f.await, None)), + None => None + } + }) +} + /// Collect all of the values of this stream into a vector, returning a /// future representing the result of that computation. /// @@ -875,6 +898,14 @@ mod tests { assert_eq!(executor::block_on(next(&mut stream)), None); } + #[test] + fn test_once() { + let stream = once(async { 17 }); + + let collection: Vec = executor::block_on(collect(stream)); + assert_eq!(collection, vec![17]); + } + #[test] fn test_collect() { let stream = iter(1..=5);