Skip to content

Commit b4ced4b

Browse files
committed
from/into stream
Signed-off-by: Yoshua Wuyts <[email protected]> update examples Signed-off-by: Yoshua Wuyts <[email protected]> impl collect Signed-off-by: Yoshua Wuyts <[email protected]> compiles! Signed-off-by: Yoshua Wuyts <[email protected]> layout base for collect into vec Signed-off-by: Yoshua Wuyts <[email protected]> fmt Signed-off-by: Yoshua Wuyts <[email protected]> progress Signed-off-by: Yoshua Wuyts <[email protected]> compiles! Signed-off-by: Yoshua Wuyts <[email protected]> define failing test Signed-off-by: Yoshua Wuyts <[email protected]> cargo fmt Signed-off-by: Yoshua Wuyts <[email protected]> stuck again Signed-off-by: Yoshua Wuyts <[email protected]> fix trait bounds! Signed-off-by: Yoshua Wuyts <[email protected]> cargo fmt Signed-off-by: Yoshua Wuyts <[email protected]> hide dyn fut impl Signed-off-by: Yoshua Wuyts <[email protected]> dyn ret for vec Signed-off-by: Yoshua Wuyts <[email protected]> cargo fmt Signed-off-by: Yoshua Wuyts <[email protected]> collect docs Signed-off-by: Yoshua Wuyts <[email protected]> remove macro from vec::from_stream Signed-off-by: Yoshua Wuyts <[email protected]> shorten collect trait bound Signed-off-by: Yoshua Wuyts <[email protected]> Remove some Unpin and Send bounds Signed-off-by: Yoshua Wuyts <[email protected]>
1 parent 265f1ff commit b4ced4b

File tree

7 files changed

+163
-3
lines changed

7 files changed

+163
-3
lines changed

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,6 @@ pub mod stream;
5252
pub mod sync;
5353
pub mod task;
5454

55+
mod vec;
56+
5557
pub(crate) mod utils;

src/stream/from_stream.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
use super::IntoStream;
2+
3+
use std::pin::Pin;
4+
5+
/// Conversion from a `Stream`.
6+
///
7+
/// By implementing `FromStream` for a type, you define how it will be created from a stream.
8+
/// This is common for types which describe a collection of some kind.
9+
///
10+
/// See also: [`IntoStream`].
11+
///
12+
/// [`IntoStream`]: trait.IntoStream.html
13+
pub trait FromStream<T> {
14+
/// Creates a value from a stream.
15+
///
16+
/// # Examples
17+
///
18+
/// Basic usage:
19+
///
20+
/// ```
21+
/// // use async_std::stream::FromStream;
22+
///
23+
/// // let _five_fives = async_std::stream::repeat(5).take(5);
24+
/// ```
25+
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
26+
stream: S,
27+
) -> Pin<Box<dyn core::future::Future<Output = Self> + 'a>>;
28+
}

src/stream/into_stream.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
use futures_core::stream::Stream;
2+
3+
/// Conversion into a `Stream`.
4+
///
5+
/// By implementing `IntoIterator` for a type, you define how it will be
6+
/// converted to an iterator. This is common for types which describe a
7+
/// collection of some kind.
8+
///
9+
/// [`from_stream`]: #tymethod.from_stream
10+
/// [`Stream`]: trait.Stream.html
11+
/// [`collect`]: trait.Stream.html#method.collect
12+
///
13+
/// See also: [`FromStream`].
14+
///
15+
/// [`FromStream`]: trait.FromStream.html
16+
pub trait IntoStream {
17+
/// The type of the elements being iterated over.
18+
type Item;
19+
20+
/// Which kind of stream are we turning this into?
21+
type IntoStream: Stream<Item = Self::Item>;
22+
23+
/// Creates a stream from a value.
24+
fn into_stream(self) -> Self::IntoStream;
25+
}
26+
27+
impl<I: Stream> IntoStream for I {
28+
type Item = I::Item;
29+
type IntoStream = I;
30+
31+
#[inline]
32+
fn into_stream(self) -> I {
33+
self
34+
}
35+
}

src/stream/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,16 @@
2323
2424
pub use double_ended_stream::DoubleEndedStream;
2525
pub use empty::{empty, Empty};
26+
pub use from_stream::FromStream;
27+
pub use into_stream::IntoStream;
2628
pub use once::{once, Once};
2729
pub use repeat::{repeat, Repeat};
2830
pub use stream::{Scan, Stream, Take, Zip};
2931

3032
mod double_ended_stream;
3133
mod empty;
34+
mod from_stream;
35+
mod into_stream;
3236
mod once;
3337
mod repeat;
3438
mod stream;

src/stream/stream/mod.rs

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,15 @@ use min_by::MinByFuture;
4646
use next::NextFuture;
4747
use nth::NthFuture;
4848

49+
use super::from_stream::FromStream;
50+
use crate::future::Future;
51+
use crate::task::{Context, Poll};
4952
use std::cmp::Ordering;
5053
use std::marker::PhantomData;
5154
use std::pin::Pin;
5255

5356
use cfg_if::cfg_if;
5457

55-
use crate::task::{Context, Poll};
56-
5758
cfg_if! {
5859
if #[cfg(feature = "docs")] {
5960
#[doc(hidden)]
@@ -76,6 +77,21 @@ cfg_if! {
7677
}
7778
}
7879

80+
cfg_if! {
81+
if #[cfg(feature = "docs")] {
82+
#[doc(hidden)]
83+
pub struct DynFuture<'a, T>(std::marker::PhantomData<&'a T>);
84+
85+
macro_rules! dyn_ret {
86+
($a:lifetime, $o:ty) => (DynFuture<$a, $o>);
87+
}
88+
} else {
89+
macro_rules! dyn_ret {
90+
($a:lifetime, $o:ty) => (Pin<Box<dyn core::future::Future<Output = $o> + 'a>>)
91+
}
92+
}
93+
}
94+
7995
/// An asynchronous stream of values.
8096
///
8197
/// This trait is an async version of [`std::iter::Iterator`].
@@ -466,7 +482,6 @@ pub trait Stream {
466482
///
467483
/// Basic usage:
468484
///
469-
/// ```
470485
/// # fn main() { async_std::task::block_on(async {
471486
/// #
472487
/// use async_std::prelude::*;
@@ -590,6 +605,48 @@ pub trait Stream {
590605
{
591606
Zip::new(self, other)
592607
}
608+
609+
/// Transforms a stream into a collection.
610+
///
611+
/// `collect()` can take anything streamable, and turn it into a relevant
612+
/// collection. This is one of the more powerful methods in the async
613+
/// standard library, used in a variety of contexts.
614+
///
615+
/// The most basic pattern in which `collect()` is used is to turn one
616+
/// collection into another. You take a collection, call [`stream`] on it,
617+
/// do a bunch of transformations, and then `collect()` at the end.
618+
///
619+
/// Because `collect()` is so general, it can cause problems with type
620+
/// inference. As such, `collect()` is one of the few times you'll see
621+
/// the syntax affectionately known as the 'turbofish': `::<>`. This
622+
/// helps the inference algorithm understand specifically which collection
623+
/// you're trying to collect into.
624+
///
625+
/// # Examples
626+
///
627+
/// ```
628+
/// # fn main() { async_std::task::block_on(async {
629+
/// #
630+
/// use async_std::prelude::*;
631+
/// use async_std::stream;
632+
///
633+
/// let s = stream::repeat(9u8).take(3);
634+
/// let buf: Vec<u8> = s.collect().await;
635+
///
636+
/// assert_eq!(buf, vec![9; 3]);
637+
/// #
638+
/// # }) }
639+
/// ```
640+
///
641+
/// [`stream`]: trait.Stream.html#tymethod.next
642+
#[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead (TODO)"]
643+
fn collect<'a, B>(self) -> dyn_ret!('a, B)
644+
where
645+
Self: futures_core::stream::Stream + Sized + 'a,
646+
B: FromStream<<Self as futures_core::stream::Stream>::Item>,
647+
{
648+
FromStream::from_stream(self)
649+
}
593650
}
594651

595652
impl<T: futures_core::stream::Stream + ?Sized> Stream for T {

src/vec/from_stream.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
use crate::stream::{FromStream, IntoStream, Stream};
2+
3+
use std::pin::Pin;
4+
5+
impl<T> FromStream<T> for Vec<T> {
6+
#[inline]
7+
fn from_stream<'a, S: IntoStream<Item = T>>(
8+
stream: S,
9+
) -> Pin<Box<dyn core::future::Future<Output = Self> + 'a>>
10+
where
11+
<S as IntoStream>::IntoStream: 'a,
12+
{
13+
let stream = stream.into_stream();
14+
15+
Pin::from(Box::new(async move {
16+
pin_utils::pin_mut!(stream);
17+
18+
let mut out = vec![];
19+
while let Some(item) = stream.next().await {
20+
out.push(item);
21+
}
22+
out
23+
}))
24+
}
25+
}

src/vec/mod.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
//! The Rust core allocation and collections library
2+
//!
3+
//! This library provides smart pointers and collections for managing
4+
//! heap-allocated values.
5+
6+
mod from_stream;
7+
8+
#[doc(inline)]
9+
pub use std::vec::Vec;

0 commit comments

Comments
 (0)