@@ -26,6 +26,7 @@ use std::pin::Pin;
26
26
27
27
use cfg_if:: cfg_if;
28
28
29
+ use super :: from_stream:: FromStream ;
29
30
use super :: min_by:: MinBy ;
30
31
use crate :: future:: Future ;
31
32
use crate :: task:: { Context , Poll } ;
@@ -51,6 +52,21 @@ cfg_if! {
51
52
}
52
53
}
53
54
55
+ cfg_if ! {
56
+ if #[ cfg( feature = "docs" ) ] {
57
+ #[ doc( hidden) ]
58
+ pub struct DynFuture <' a, T >( std:: marker:: PhantomData <& ' a T >) ;
59
+
60
+ macro_rules! dyn_ret {
61
+ ( $a: lifetime, $o: ty) => ( DynFuture <$a, $o>) ;
62
+ }
63
+ } else {
64
+ macro_rules! dyn_ret {
65
+ ( $a: lifetime, $o: ty) => ( Pin <Box <dyn core:: future:: Future <Output = $o> + ' a>>)
66
+ }
67
+ }
68
+ }
69
+
54
70
/// An asynchronous stream of values.
55
71
///
56
72
/// This trait is an async version of [`std::iter::Iterator`].
@@ -227,7 +243,6 @@ pub trait Stream {
227
243
///
228
244
/// Basic usage:
229
245
///
230
- /// ```
231
246
/// # fn main() { async_std::task::block_on(async {
232
247
/// #
233
248
/// use async_std::prelude::*;
@@ -266,6 +281,48 @@ pub trait Stream {
266
281
f,
267
282
}
268
283
}
284
+
285
+ /// Transforms a stream into a collection.
286
+ ///
287
+ /// `collect()` can take anything streamable, and turn it into a relevant
288
+ /// collection. This is one of the more powerful methods in the async
289
+ /// standard library, used in a variety of contexts.
290
+ ///
291
+ /// The most basic pattern in which `collect()` is used is to turn one
292
+ /// collection into another. You take a collection, call [`stream`] on it,
293
+ /// do a bunch of transformations, and then `collect()` at the end.
294
+ ///
295
+ /// Because `collect()` is so general, it can cause problems with type
296
+ /// inference. As such, `collect()` is one of the few times you'll see
297
+ /// the syntax affectionately known as the 'turbofish': `::<>`. This
298
+ /// helps the inference algorithm understand specifically which collection
299
+ /// you're trying to collect into.
300
+ ///
301
+ /// # Examples
302
+ ///
303
+ /// ```
304
+ /// # fn main() { async_std::task::block_on(async {
305
+ /// #
306
+ /// use async_std::prelude::*;
307
+ /// use async_std::stream;
308
+ ///
309
+ /// let s = stream::repeat(9u8).take(3);
310
+ /// let buf: Vec<u8> = s.collect().await;
311
+ ///
312
+ /// assert_eq!(buf, vec![9; 3]);
313
+ /// #
314
+ /// # }) }
315
+ /// ```
316
+ ///
317
+ /// [`stream`]: trait.Stream.html#tymethod.next
318
+ #[ must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead (TODO)" ]
319
+ fn collect < ' a , B > ( self ) -> dyn_ret ! ( ' a, B )
320
+ where
321
+ Self : futures:: stream:: Stream + Sized + ' a ,
322
+ B : FromStream < <Self as futures:: stream:: Stream >:: Item > ,
323
+ {
324
+ FromStream :: from_stream ( self )
325
+ }
269
326
}
270
327
271
328
impl < T : futures_core:: stream:: Stream + Unpin + ?Sized > Stream for T {
0 commit comments