Skip to main content

futures_util/stream/stream/
mod.rs

1//! Streams
2//!
3//! This module contains a number of functions for working with `Stream`s,
4//! including the `StreamExt` trait which adds methods to `Stream` types.
5
6use crate::future::{assert_future, Either};
7use crate::stream::assert_stream;
8#[cfg(feature = "alloc")]
9use alloc::boxed::Box;
10#[cfg(feature = "alloc")]
11use alloc::vec::Vec;
12use core::pin::Pin;
13#[cfg(feature = "sink")]
14use futures_core::stream::TryStream;
15#[cfg(feature = "alloc")]
16use futures_core::stream::{BoxStream, LocalBoxStream};
17use futures_core::{
18    future::Future,
19    stream::{FusedStream, Stream},
20    task::{Context, Poll},
21};
22#[cfg(feature = "sink")]
23use futures_sink::Sink;
24
25use crate::fns::{inspect_fn, InspectFn};
26
27mod chain;
28#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
29pub use self::chain::Chain;
30
31mod collect;
32#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
33pub use self::collect::Collect;
34
35mod unzip;
36#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
37pub use self::unzip::Unzip;
38
39mod concat;
40#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
41pub use self::concat::Concat;
42
43mod count;
44#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
45pub use self::count::Count;
46
47mod cycle;
48#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
49pub use self::cycle::Cycle;
50
51mod enumerate;
52#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
53pub use self::enumerate::Enumerate;
54
55mod filter;
56#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
57pub use self::filter::Filter;
58
59mod filter_map;
60#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
61pub use self::filter_map::FilterMap;
62
63mod flatten;
64
65delegate_all!(
66    /// Stream for the [`flatten`](StreamExt::flatten) method.
67    Flatten<St>(
68        flatten::Flatten<St, St::Item>
69    ): Debug + Sink + Stream + FusedStream + AccessInner[St, (.)] + New[|x: St| flatten::Flatten::new(x)]
70    where St: Stream
71);
72
73mod fold;
74#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
75pub use self::fold::Fold;
76
77mod any;
78#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
79pub use self::any::Any;
80
81mod all;
82#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
83pub use self::all::All;
84
85#[cfg(feature = "sink")]
86mod forward;
87
88#[cfg(feature = "sink")]
89delegate_all!(
90    /// Future for the [`forward`](super::StreamExt::forward) method.
91    #[cfg_attr(docsrs, doc(cfg(feature = "sink")))]
92    Forward<St, Si>(
93        forward::Forward<St, Si, St::Ok>
94    ): Debug + Future + FusedFuture + New[|x: St, y: Si| forward::Forward::new(x, y)]
95    where St: TryStream
96);
97
98mod for_each;
99#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
100pub use self::for_each::ForEach;
101
102mod fuse;
103#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
104pub use self::fuse::Fuse;
105
106mod into_future;
107#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
108pub use self::into_future::StreamFuture;
109
110delegate_all!(
111    /// Stream for the [`inspect`](StreamExt::inspect) method.
112    Inspect<St, F>(
113        map::Map<St, InspectFn<F>>
114    ): Debug + Sink + Stream + FusedStream + AccessInner[St, (.)] + New[|x: St, f: F| map::Map::new(x, inspect_fn(f))]
115);
116
117mod map;
118#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
119pub use self::map::Map;
120
121delegate_all!(
122    /// Stream for the [`flat_map`](StreamExt::flat_map) method.
123    FlatMap<St, U, F>(
124        flatten::Flatten<Map<St, F>, U>
125    ): Debug + Sink + Stream + FusedStream + AccessInner[St, (. .)] + New[|x: St, f: F| flatten::Flatten::new(Map::new(x, f))]
126);
127
128mod next;
129#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
130pub use self::next::Next;
131
132mod select_next_some;
133#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
134pub use self::select_next_some::SelectNextSome;
135
136mod peek;
137#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
138pub use self::peek::{NextIf, NextIfEq, Peek, PeekMut, Peekable};
139
140mod skip;
141#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
142pub use self::skip::Skip;
143
144mod skip_while;
145#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
146pub use self::skip_while::SkipWhile;
147
148mod take;
149#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
150pub use self::take::Take;
151
152mod take_while;
153#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
154pub use self::take_while::TakeWhile;
155
156mod take_until;
157#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
158pub use self::take_until::TakeUntil;
159
160mod then;
161#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
162pub use self::then::Then;
163
164mod zip;
165#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
166pub use self::zip::Zip;
167
168#[cfg(feature = "alloc")]
169mod chunks;
170#[cfg(feature = "alloc")]
171#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
172pub use self::chunks::Chunks;
173
174#[cfg(feature = "alloc")]
175mod ready_chunks;
176#[cfg(feature = "alloc")]
177#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
178pub use self::ready_chunks::ReadyChunks;
179
180mod scan;
181#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
182pub use self::scan::Scan;
183
184#[cfg(target_has_atomic = "ptr")]
185#[cfg(feature = "alloc")]
186mod buffer_unordered;
187#[cfg(target_has_atomic = "ptr")]
188#[cfg(feature = "alloc")]
189#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
190pub use self::buffer_unordered::BufferUnordered;
191
192#[cfg(target_has_atomic = "ptr")]
193#[cfg(feature = "alloc")]
194mod buffered;
195#[cfg(target_has_atomic = "ptr")]
196#[cfg(feature = "alloc")]
197#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
198pub use self::buffered::Buffered;
199
200#[cfg(target_has_atomic = "ptr")]
201#[cfg(feature = "alloc")]
202pub(crate) mod flatten_unordered;
203
204#[cfg(target_has_atomic = "ptr")]
205#[cfg(feature = "alloc")]
206#[allow(unreachable_pub)]
207pub use self::flatten_unordered::FlattenUnordered;
208
209#[cfg(target_has_atomic = "ptr")]
210#[cfg(feature = "alloc")]
211delegate_all!(
212    /// Stream for the [`flat_map_unordered`](StreamExt::flat_map_unordered) method.
213    FlatMapUnordered<St, U, F>(
214        FlattenUnordered<Map<St, F>>
215    ): Debug + Sink + Stream + FusedStream + AccessInner[St, (. .)] + New[|x: St, limit: Option<usize>, f: F| FlattenUnordered::new(Map::new(x, f), limit)]
216    where St: Stream, U: Stream, U: Unpin, F: FnMut(St::Item) -> U
217);
218
219#[cfg(target_has_atomic = "ptr")]
220#[cfg(feature = "alloc")]
221mod for_each_concurrent;
222#[cfg(target_has_atomic = "ptr")]
223#[cfg(feature = "alloc")]
224#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
225pub use self::for_each_concurrent::ForEachConcurrent;
226
227#[cfg(target_has_atomic = "ptr")]
228#[cfg(feature = "sink")]
229#[cfg_attr(docsrs, doc(cfg(feature = "sink")))]
230#[cfg(feature = "alloc")]
231mod split;
232#[cfg(target_has_atomic = "ptr")]
233#[cfg(feature = "sink")]
234#[cfg_attr(docsrs, doc(cfg(feature = "sink")))]
235#[cfg(feature = "alloc")]
236#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
237pub use self::split::{ReuniteError, SplitSink, SplitStream};
238
239#[cfg(feature = "std")]
240mod catch_unwind;
241#[cfg(feature = "std")]
242#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
243pub use self::catch_unwind::CatchUnwind;
244
245impl<T: ?Sized> StreamExt for T where T: Stream {}
246
247/// An extension trait for `Stream`s that provides a variety of convenient
248/// combinator functions.
249pub trait StreamExt: Stream {
250    /// Creates a future that resolves to the next item in the stream.
251    ///
252    /// Note that because `next` doesn't take ownership over the stream,
253    /// the [`Stream`] type must be [`Unpin`]. If you want to use `next` with a
254    /// [`!Unpin`](Unpin) stream, you'll first have to pin the stream. This can
255    /// be done by boxing the stream using [`Box::pin`] or
256    /// pinning it to the stack using the `pin_mut!` macro from the `pin_utils`
257    /// crate.
258    ///
259    /// # Examples
260    ///
261    /// ```
262    /// # futures::executor::block_on(async {
263    /// use futures::stream::{self, StreamExt};
264    ///
265    /// let mut stream = stream::iter(1..=3);
266    ///
267    /// assert_eq!(stream.next().await, Some(1));
268    /// assert_eq!(stream.next().await, Some(2));
269    /// assert_eq!(stream.next().await, Some(3));
270    /// assert_eq!(stream.next().await, None);
271    /// # });
272    /// ```
273    fn next(&mut self) -> Next<'_, Self>
274    where
275        Self: Unpin,
276    {
277        assert_future::<Option<Self::Item>, _>(Next::new(self))
278    }
279
280    /// Converts this stream into a future of `(next_item, tail_of_stream)`.
281    /// If the stream terminates, then the next item is [`None`].
282    ///
283    /// The returned future can be used to compose streams and futures together
284    /// by placing everything into the "world of futures".
285    ///
286    /// Note that because `into_future` moves the stream, the [`Stream`] type
287    /// must be [`Unpin`]. If you want to use `into_future` with a
288    /// [`!Unpin`](Unpin) stream, you'll first have to pin the stream. This can
289    /// be done by boxing the stream using [`Box::pin`] or
290    /// pinning it to the stack using the `pin_mut!` macro from the `pin_utils`
291    /// crate.
292    ///
293    /// # Examples
294    ///
295    /// ```
296    /// # futures::executor::block_on(async {
297    /// use futures::stream::{self, StreamExt};
298    ///
299    /// let stream = stream::iter(1..=3);
300    ///
301    /// let (item, stream) = stream.into_future().await;
302    /// assert_eq!(Some(1), item);
303    ///
304    /// let (item, stream) = stream.into_future().await;
305    /// assert_eq!(Some(2), item);
306    /// # });
307    /// ```
308    fn into_future(self) -> StreamFuture<Self>
309    where
310        Self: Sized + Unpin,
311    {
312        assert_future::<(Option<Self::Item>, Self), _>(StreamFuture::new(self))
313    }
314
315    /// Maps this stream's items to a different type, returning a new stream of
316    /// the resulting type.
317    ///
318    /// The provided closure is executed over all elements of this stream as
319    /// they are made available. It is executed inline with calls to
320    /// [`poll_next`](Stream::poll_next).
321    ///
322    /// Note that this function consumes the stream passed into it and returns a
323    /// wrapped version of it, similar to the existing `map` methods in the
324    /// standard library.
325    ///
326    /// See [`StreamExt::then`](Self::then) if you want to use a closure that
327    /// returns a future instead of a value.
328    ///
329    /// # Examples
330    ///
331    /// ```
332    /// # futures::executor::block_on(async {
333    /// use futures::stream::{self, StreamExt};
334    ///
335    /// let stream = stream::iter(1..=3);
336    /// let stream = stream.map(|x| x + 3);
337    ///
338    /// assert_eq!(vec![4, 5, 6], stream.collect::<Vec<_>>().await);
339    /// # });
340    /// ```
341    fn map<T, F>(self, f: F) -> Map<Self, F>
342    where
343        F: FnMut(Self::Item) -> T,
344        Self: Sized,
345    {
346        assert_stream::<T, _>(Map::new(self, f))
347    }
348
349    /// Creates a stream which gives the current iteration count as well as
350    /// the next value.
351    ///
352    /// The stream returned yields pairs `(i, val)`, where `i` is the
353    /// current index of iteration and `val` is the value returned by the
354    /// stream.
355    ///
356    /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
357    /// different sized integer, the [`zip`](StreamExt::zip) function provides similar
358    /// functionality.
359    ///
360    /// # Overflow Behavior
361    ///
362    /// The method does no guarding against overflows, so enumerating more than
363    /// [`usize::MAX`] elements either produces the wrong result or panics. If
364    /// debug assertions are enabled, a panic is guaranteed.
365    ///
366    /// # Panics
367    ///
368    /// The returned stream might panic if the to-be-returned index would
369    /// overflow a [`usize`].
370    ///
371    /// # Examples
372    ///
373    /// ```
374    /// # futures::executor::block_on(async {
375    /// use futures::stream::{self, StreamExt};
376    ///
377    /// let stream = stream::iter(vec!['a', 'b', 'c']);
378    ///
379    /// let mut stream = stream.enumerate();
380    ///
381    /// assert_eq!(stream.next().await, Some((0, 'a')));
382    /// assert_eq!(stream.next().await, Some((1, 'b')));
383    /// assert_eq!(stream.next().await, Some((2, 'c')));
384    /// assert_eq!(stream.next().await, None);
385    /// # });
386    /// ```
387    fn enumerate(self) -> Enumerate<Self>
388    where
389        Self: Sized,
390    {
391        assert_stream::<(usize, Self::Item), _>(Enumerate::new(self))
392    }
393
394    /// Filters the values produced by this stream according to the provided
395    /// asynchronous predicate.
396    ///
397    /// As values of this stream are made available, the provided predicate `f`
398    /// will be run against them. If the predicate returns a `Future` which
399    /// resolves to `true`, then the stream will yield the value, but if the
400    /// predicate returns a `Future` which resolves to `false`, then the value
401    /// will be discarded and the next value will be produced.
402    ///
403    /// Note that this function consumes the stream passed into it and returns a
404    /// wrapped version of it, similar to the existing `filter` methods in the
405    /// standard library.
406    ///
407    /// # Examples
408    ///
409    /// ```
410    /// # futures::executor::block_on(async {
411    /// use futures::future;
412    /// use futures::stream::{self, StreamExt};
413    ///
414    /// let stream = stream::iter(1..=10);
415    /// let events = stream.filter(|x| future::ready(x % 2 == 0));
416    ///
417    /// assert_eq!(vec![2, 4, 6, 8, 10], events.collect::<Vec<_>>().await);
418    /// # });
419    /// ```
420    fn filter<Fut, F>(self, f: F) -> Filter<Self, Fut, F>
421    where
422        F: FnMut(&Self::Item) -> Fut,
423        Fut: Future<Output = bool>,
424        Self: Sized,
425    {
426        assert_stream::<Self::Item, _>(Filter::new(self, f))
427    }
428
429    /// Filters the values produced by this stream while simultaneously mapping
430    /// them to a different type according to the provided asynchronous closure.
431    ///
432    /// As values of this stream are made available, the provided function will
433    /// be run on them. If the future returned by the predicate `f` resolves to
434    /// [`Some(item)`](Some) then the stream will yield the value `item`, but if
435    /// it resolves to [`None`] then the next value will be produced.
436    ///
437    /// Note that this function consumes the stream passed into it and returns a
438    /// wrapped version of it, similar to the existing `filter_map` methods in
439    /// the standard library.
440    ///
441    /// # Examples
442    /// ```
443    /// # futures::executor::block_on(async {
444    /// use futures::stream::{self, StreamExt};
445    ///
446    /// let stream = stream::iter(1..=10);
447    /// let events = stream.filter_map(|x| async move {
448    ///     if x % 2 == 0 { Some(x + 1) } else { None }
449    /// });
450    ///
451    /// assert_eq!(vec![3, 5, 7, 9, 11], events.collect::<Vec<_>>().await);
452    /// # });
453    /// ```
454    fn filter_map<Fut, T, F>(self, f: F) -> FilterMap<Self, Fut, F>
455    where
456        F: FnMut(Self::Item) -> Fut,
457        Fut: Future<Output = Option<T>>,
458        Self: Sized,
459    {
460        assert_stream::<T, _>(FilterMap::new(self, f))
461    }
462
463    /// Computes from this stream's items new items of a different type using
464    /// an asynchronous closure.
465    ///
466    /// The provided closure `f` will be called with an `Item` once a value is
467    /// ready, it returns a future which will then be run to completion
468    /// to produce the next value on this stream.
469    ///
470    /// Note that this function consumes the stream passed into it and returns a
471    /// wrapped version of it.
472    ///
473    /// See [`StreamExt::map`](Self::map) if you want to use a closure that
474    /// returns a value instead of a future.
475    ///
476    /// # Examples
477    ///
478    /// ```
479    /// # futures::executor::block_on(async {
480    /// use futures::stream::{self, StreamExt};
481    ///
482    /// let stream = stream::iter(1..=3);
483    /// let stream = stream.then(|x| async move { x + 3 });
484    ///
485    /// assert_eq!(vec![4, 5, 6], stream.collect::<Vec<_>>().await);
486    /// # });
487    /// ```
488    fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
489    where
490        F: FnMut(Self::Item) -> Fut,
491        Fut: Future,
492        Self: Sized,
493    {
494        assert_stream::<Fut::Output, _>(Then::new(self, f))
495    }
496
497    /// Transforms a stream into a collection, returning a
498    /// future representing the result of that computation.
499    ///
500    /// The returned future will be resolved when the stream terminates.
501    ///
502    /// # Examples
503    ///
504    /// ```
505    /// # futures::executor::block_on(async {
506    /// use futures::channel::mpsc;
507    /// use futures::stream::StreamExt;
508    /// use std::thread;
509    ///
510    /// let (tx, rx) = mpsc::unbounded();
511    ///
512    /// thread::spawn(move || {
513    ///     for i in 1..=5 {
514    ///         tx.unbounded_send(i).unwrap();
515    ///     }
516    /// });
517    ///
518    /// let output = rx.collect::<Vec<i32>>().await;
519    /// assert_eq!(output, vec![1, 2, 3, 4, 5]);
520    /// # });
521    /// ```
522    fn collect<C: Default + Extend<Self::Item>>(self) -> Collect<Self, C>
523    where
524        Self: Sized,
525    {
526        assert_future::<C, _>(Collect::new(self))
527    }
528
529    /// Converts a stream of pairs into a future, which
530    /// resolves to pair of containers.
531    ///
532    /// `unzip()` produces a future, which resolves to two
533    /// collections: one from the left elements of the pairs,
534    /// and one from the right elements.
535    ///
536    /// The returned future will be resolved when the stream terminates.
537    ///
538    /// # Examples
539    ///
540    /// ```
541    /// # futures::executor::block_on(async {
542    /// use futures::channel::mpsc;
543    /// use futures::stream::StreamExt;
544    /// use std::thread;
545    ///
546    /// let (tx, rx) = mpsc::unbounded();
547    ///
548    /// thread::spawn(move || {
549    ///     tx.unbounded_send((1, 2)).unwrap();
550    ///     tx.unbounded_send((3, 4)).unwrap();
551    ///     tx.unbounded_send((5, 6)).unwrap();
552    /// });
553    ///
554    /// let (o1, o2): (Vec<_>, Vec<_>) = rx.unzip().await;
555    /// assert_eq!(o1, vec![1, 3, 5]);
556    /// assert_eq!(o2, vec![2, 4, 6]);
557    /// # });
558    /// ```
559    fn unzip<A, B, FromA, FromB>(self) -> Unzip<Self, FromA, FromB>
560    where
561        FromA: Default + Extend<A>,
562        FromB: Default + Extend<B>,
563        Self: Sized + Stream<Item = (A, B)>,
564    {
565        assert_future::<(FromA, FromB), _>(Unzip::new(self))
566    }
567
568    /// Concatenate all items of a stream into a single extendable
569    /// destination, returning a future representing the end result.
570    ///
571    /// This combinator will extend the first item with the contents
572    /// of all the subsequent results of the stream. If the stream is
573    /// empty, the default value will be returned.
574    ///
575    /// Works with all collections that implement the [`Extend`] trait.
576    ///
577    /// # Examples
578    ///
579    /// ```
580    /// # futures::executor::block_on(async {
581    /// use futures::channel::mpsc;
582    /// use futures::stream::StreamExt;
583    /// use std::thread;
584    ///
585    /// let (tx, rx) = mpsc::unbounded();
586    ///
587    /// thread::spawn(move || {
588    ///     for i in (0..3).rev() {
589    ///         let n = i * 3;
590    ///         tx.unbounded_send(vec![n + 1, n + 2, n + 3]).unwrap();
591    ///     }
592    /// });
593    ///
594    /// let result = rx.concat().await;
595    ///
596    /// assert_eq!(result, vec![7, 8, 9, 4, 5, 6, 1, 2, 3]);
597    /// # });
598    /// ```
599    fn concat(self) -> Concat<Self>
600    where
601        Self: Sized,
602        Self::Item: Extend<<<Self as Stream>::Item as IntoIterator>::Item> + IntoIterator + Default,
603    {
604        assert_future::<Self::Item, _>(Concat::new(self))
605    }
606
607    /// Drives the stream to completion, counting the number of items.
608    ///
609    /// # Overflow Behavior
610    ///
611    /// The method does no guarding against overflows, so counting elements of a
612    /// stream with more than [`usize::MAX`] elements either produces the wrong
613    /// result or panics. If debug assertions are enabled, a panic is guaranteed.
614    ///
615    /// # Panics
616    ///
617    /// This function might panic if the iterator has more than [`usize::MAX`]
618    /// elements.
619    ///
620    /// # Examples
621    ///
622    /// ```
623    /// # futures::executor::block_on(async {
624    /// use futures::stream::{self, StreamExt};
625    ///
626    /// let stream = stream::iter(1..=10);
627    /// let count = stream.count().await;
628    ///
629    /// assert_eq!(count, 10);
630    /// # });
631    /// ```
632    fn count(self) -> Count<Self>
633    where
634        Self: Sized,
635    {
636        assert_future::<usize, _>(Count::new(self))
637    }
638
639    /// Repeats a stream endlessly.
640    ///
641    /// The stream never terminates. Note that you likely want to avoid
642    /// usage of `collect` or such on the returned stream as it will exhaust
643    /// available memory as it tries to just fill up all RAM.
644    ///
645    /// # Examples
646    ///
647    /// ```
648    /// # futures::executor::block_on(async {
649    /// use futures::stream::{self, StreamExt};
650    /// let a = [1, 2, 3];
651    /// let mut s = stream::iter(a.iter()).cycle();
652    ///
653    /// assert_eq!(s.next().await, Some(&1));
654    /// assert_eq!(s.next().await, Some(&2));
655    /// assert_eq!(s.next().await, Some(&3));
656    /// assert_eq!(s.next().await, Some(&1));
657    /// assert_eq!(s.next().await, Some(&2));
658    /// assert_eq!(s.next().await, Some(&3));
659    /// assert_eq!(s.next().await, Some(&1));
660    /// # });
661    /// ```
662    fn cycle(self) -> Cycle<Self>
663    where
664        Self: Sized + Clone,
665    {
666        assert_stream::<Self::Item, _>(Cycle::new(self))
667    }
668
669    /// Execute an accumulating asynchronous computation over a stream,
670    /// collecting all the values into one final result.
671    ///
672    /// This combinator will accumulate all values returned by this stream
673    /// according to the closure provided. The initial state is also provided to
674    /// this method and then is returned again by each execution of the closure.
675    /// Once the entire stream has been exhausted the returned future will
676    /// resolve to this value.
677    ///
678    /// # Examples
679    ///
680    /// ```
681    /// # futures::executor::block_on(async {
682    /// use futures::stream::{self, StreamExt};
683    ///
684    /// let number_stream = stream::iter(0..6);
685    /// let sum = number_stream.fold(0, |acc, x| async move { acc + x });
686    /// assert_eq!(sum.await, 15);
687    /// # });
688    /// ```
689    fn fold<T, Fut, F>(self, init: T, f: F) -> Fold<Self, Fut, T, F>
690    where
691        F: FnMut(T, Self::Item) -> Fut,
692        Fut: Future<Output = T>,
693        Self: Sized,
694    {
695        assert_future::<T, _>(Fold::new(self, f, init))
696    }
697
698    /// Execute predicate over asynchronous stream, and return `true` if any element in stream satisfied a predicate.
699    ///
700    /// # Examples
701    ///
702    /// ```
703    /// # futures::executor::block_on(async {
704    /// use futures::stream::{self, StreamExt};
705    ///
706    /// let number_stream = stream::iter(0..10);
707    /// let contain_three = number_stream.any(|i| async move { i == 3 });
708    /// assert_eq!(contain_three.await, true);
709    /// # });
710    /// ```
711    fn any<Fut, F>(self, f: F) -> Any<Self, Fut, F>
712    where
713        F: FnMut(Self::Item) -> Fut,
714        Fut: Future<Output = bool>,
715        Self: Sized,
716    {
717        assert_future::<bool, _>(Any::new(self, f))
718    }
719
720    /// Execute predicate over asynchronous stream, and return `true` if all element in stream satisfied a predicate.
721    ///
722    /// # Examples
723    ///
724    /// ```
725    /// # futures::executor::block_on(async {
726    /// use futures::stream::{self, StreamExt};
727    ///
728    /// let number_stream = stream::iter(0..10);
729    /// let less_then_twenty = number_stream.all(|i| async move { i < 20 });
730    /// assert_eq!(less_then_twenty.await, true);
731    /// # });
732    /// ```
733    fn all<Fut, F>(self, f: F) -> All<Self, Fut, F>
734    where
735        F: FnMut(Self::Item) -> Fut,
736        Fut: Future<Output = bool>,
737        Self: Sized,
738    {
739        assert_future::<bool, _>(All::new(self, f))
740    }
741
742    /// Flattens a stream of streams into just one continuous stream.
743    ///
744    /// # Examples
745    ///
746    /// ```
747    /// # futures::executor::block_on(async {
748    /// use futures::channel::mpsc;
749    /// use futures::stream::StreamExt;
750    /// use std::thread;
751    ///
752    /// let (tx1, rx1) = mpsc::unbounded();
753    /// let (tx2, rx2) = mpsc::unbounded();
754    /// let (tx3, rx3) = mpsc::unbounded();
755    ///
756    /// thread::spawn(move || {
757    ///     tx1.unbounded_send(1).unwrap();
758    ///     tx1.unbounded_send(2).unwrap();
759    /// });
760    /// thread::spawn(move || {
761    ///     tx2.unbounded_send(3).unwrap();
762    ///     tx2.unbounded_send(4).unwrap();
763    /// });
764    /// thread::spawn(move || {
765    ///     tx3.unbounded_send(rx1).unwrap();
766    ///     tx3.unbounded_send(rx2).unwrap();
767    /// });
768    ///
769    /// let output = rx3.flatten().collect::<Vec<i32>>().await;
770    /// assert_eq!(output, vec![1, 2, 3, 4]);
771    /// # });
772    /// ```
773    fn flatten(self) -> Flatten<Self>
774    where
775        Self::Item: Stream,
776        Self: Sized,
777    {
778        assert_stream::<<Self::Item as Stream>::Item, _>(Flatten::new(self))
779    }
780
781    /// Flattens a stream of streams into just one continuous stream. Polls
782    /// inner streams produced by the base stream concurrently.
783    ///
784    /// The only argument is an optional limit on the number of concurrently
785    /// polled streams. If this limit is not `None`, no more than `limit` streams
786    /// will be polled at the same time. The `limit` argument is of type
787    /// `Into<Option<usize>>`, and so can be provided as either `None`,
788    /// `Some(10)`, or just `10`. Note: a limit of zero is interpreted as
789    /// no limit at all, and will have the same result as passing in `None`.
790    ///
791    /// # Examples
792    ///
793    /// ```
794    /// # futures::executor::block_on(async {
795    /// use futures::channel::mpsc;
796    /// use futures::stream::StreamExt;
797    /// use std::thread;
798    ///
799    /// let (tx1, rx1) = mpsc::unbounded();
800    /// let (tx2, rx2) = mpsc::unbounded();
801    /// let (tx3, rx3) = mpsc::unbounded();
802    ///
803    /// thread::spawn(move || {
804    ///     tx1.unbounded_send(1).unwrap();
805    ///     tx1.unbounded_send(2).unwrap();
806    /// });
807    /// thread::spawn(move || {
808    ///     tx2.unbounded_send(3).unwrap();
809    ///     tx2.unbounded_send(4).unwrap();
810    /// });
811    /// thread::spawn(move || {
812    ///     tx3.unbounded_send(rx1).unwrap();
813    ///     tx3.unbounded_send(rx2).unwrap();
814    /// });
815    ///
816    /// let mut output = rx3.flatten_unordered(None).collect::<Vec<i32>>().await;
817    /// output.sort();
818    ///
819    /// assert_eq!(output, vec![1, 2, 3, 4]);
820    /// # });
821    /// ```
822    #[cfg(target_has_atomic = "ptr")]
823    #[cfg(feature = "alloc")]
824    fn flatten_unordered(self, limit: impl Into<Option<usize>>) -> FlattenUnordered<Self>
825    where
826        Self::Item: Stream + Unpin,
827        Self: Sized,
828    {
829        assert_stream::<<Self::Item as Stream>::Item, _>(FlattenUnordered::new(self, limit.into()))
830    }
831
832    /// Maps a stream like [`StreamExt::map`] but flattens nested `Stream`s.
833    ///
834    /// [`StreamExt::map`] is very useful, but if it produces a `Stream` instead,
835    /// you would have to chain combinators like `.map(f).flatten()` while this
836    /// combinator provides ability to write `.flat_map(f)` instead of chaining.
837    ///
838    /// The provided closure which produces inner streams is executed over all elements
839    /// of stream as last inner stream is terminated and next stream item is available.
840    ///
841    /// Note that this function consumes the stream passed into it and returns a
842    /// wrapped version of it, similar to the existing `flat_map` methods in the
843    /// standard library.
844    ///
845    /// # Examples
846    ///
847    /// ```
848    /// # futures::executor::block_on(async {
849    /// use futures::stream::{self, StreamExt};
850    ///
851    /// let stream = stream::iter(1..=3);
852    /// let stream = stream.flat_map(|x| stream::iter(vec![x + 3; x]));
853    ///
854    /// assert_eq!(vec![4, 5, 5, 6, 6, 6], stream.collect::<Vec<_>>().await);
855    /// # });
856    /// ```
857    fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
858    where
859        F: FnMut(Self::Item) -> U,
860        U: Stream,
861        Self: Sized,
862    {
863        assert_stream::<U::Item, _>(FlatMap::new(self, f))
864    }
865
866    /// Maps a stream like [`StreamExt::map`] but flattens nested `Stream`s
867    /// and polls them concurrently, yielding items in any order, as they made
868    /// available.
869    ///
870    /// [`StreamExt::map`] is very useful, but if it produces `Stream`s
871    /// instead, and you need to poll all of them concurrently, you would
872    /// have to use something like `for_each_concurrent` and merge values
873    /// by hand. This combinator provides ability to collect all values
874    /// from concurrently polled streams into one stream.
875    ///
876    /// The first argument is an optional limit on the number of concurrently
877    /// polled streams. If this limit is not `None`, no more than `limit` streams
878    /// will be polled at the same time. The `limit` argument is of type
879    /// `Into<Option<usize>>`, and so can be provided as either `None`,
880    /// `Some(10)`, or just `10`. Note: a limit of zero is interpreted as
881    /// no limit at all, and will have the same result as passing in `None`.
882    ///
883    /// The provided closure which produces inner streams is executed over
884    /// all elements of stream as next stream item is available and limit
885    /// of concurrently processed streams isn't exceeded.
886    ///
887    /// Note that this function consumes the stream passed into it and
888    /// returns a wrapped version of it.
889    ///
890    /// # Examples
891    ///
892    /// ```
893    /// # futures::executor::block_on(async {
894    /// use futures::stream::{self, StreamExt};
895    ///
896    /// let stream = stream::iter(1..5);
897    /// let stream = stream.flat_map_unordered(1, |x| stream::iter(vec![x; x]));
898    /// let mut values = stream.collect::<Vec<_>>().await;
899    /// values.sort();
900    ///
901    /// assert_eq!(vec![1usize, 2, 2, 3, 3, 3, 4, 4, 4, 4], values);
902    /// # });
903    /// ```
904    #[cfg(target_has_atomic = "ptr")]
905    #[cfg(feature = "alloc")]
906    fn flat_map_unordered<U, F>(
907        self,
908        limit: impl Into<Option<usize>>,
909        f: F,
910    ) -> FlatMapUnordered<Self, U, F>
911    where
912        U: Stream + Unpin,
913        F: FnMut(Self::Item) -> U,
914        Self: Sized,
915    {
916        assert_stream::<U::Item, _>(FlatMapUnordered::new(self, limit.into(), f))
917    }
918
919    /// Combinator similar to [`StreamExt::fold`] that holds internal state
920    /// and produces a new stream.
921    ///
922    /// Accepts initial state and closure which will be applied to each element
923    /// of the stream until provided closure returns `None`. Once `None` is
924    /// returned, stream will be terminated.
925    ///
926    /// # Examples
927    ///
928    /// ```
929    /// # futures::executor::block_on(async {
930    /// use futures::future;
931    /// use futures::stream::{self, StreamExt};
932    ///
933    /// let stream = stream::iter(1..=10);
934    ///
935    /// let stream = stream.scan(0, |state, x| {
936    ///     *state += x;
937    ///     future::ready(if *state < 10 { Some(x) } else { None })
938    /// });
939    ///
940    /// assert_eq!(vec![1, 2, 3], stream.collect::<Vec<_>>().await);
941    /// # });
942    /// ```
943    fn scan<S, B, Fut, F>(self, initial_state: S, f: F) -> Scan<Self, S, Fut, F>
944    where
945        F: FnMut(&mut S, Self::Item) -> Fut,
946        Fut: Future<Output = Option<B>>,
947        Self: Sized,
948    {
949        assert_stream::<B, _>(Scan::new(self, initial_state, f))
950    }
951
952    /// Skip elements on this stream while the provided asynchronous predicate
953    /// resolves to `true`.
954    ///
955    /// This function, like `Iterator::skip_while`, will skip elements on the
956    /// stream until the predicate `f` resolves to `false`. Once one element
957    /// returns `false`, all future elements will be returned from the underlying
958    /// stream.
959    ///
960    /// # Examples
961    ///
962    /// ```
963    /// # futures::executor::block_on(async {
964    /// use futures::future;
965    /// use futures::stream::{self, StreamExt};
966    ///
967    /// let stream = stream::iter(1..=10);
968    ///
969    /// let stream = stream.skip_while(|x| future::ready(*x <= 5));
970    ///
971    /// assert_eq!(vec![6, 7, 8, 9, 10], stream.collect::<Vec<_>>().await);
972    /// # });
973    /// ```
974    fn skip_while<Fut, F>(self, f: F) -> SkipWhile<Self, Fut, F>
975    where
976        F: FnMut(&Self::Item) -> Fut,
977        Fut: Future<Output = bool>,
978        Self: Sized,
979    {
980        assert_stream::<Self::Item, _>(SkipWhile::new(self, f))
981    }
982
983    /// Take elements from this stream while the provided asynchronous predicate
984    /// resolves to `true`.
985    ///
986    /// This function, like `Iterator::take_while`, will take elements from the
987    /// stream until the predicate `f` resolves to `false`. Once one element
988    /// returns `false`, it will always return that the stream is done.
989    ///
990    /// # Examples
991    ///
992    /// ```
993    /// # futures::executor::block_on(async {
994    /// use futures::future;
995    /// use futures::stream::{self, StreamExt};
996    ///
997    /// let stream = stream::iter(1..=10);
998    ///
999    /// let stream = stream.take_while(|x| future::ready(*x <= 5));
1000    ///
1001    /// assert_eq!(vec![1, 2, 3, 4, 5], stream.collect::<Vec<_>>().await);
1002    /// # });
1003    /// ```
1004    fn take_while<Fut, F>(self, f: F) -> TakeWhile<Self, Fut, F>
1005    where
1006        F: FnMut(&Self::Item) -> Fut,
1007        Fut: Future<Output = bool>,
1008        Self: Sized,
1009    {
1010        assert_stream::<Self::Item, _>(TakeWhile::new(self, f))
1011    }
1012
1013    /// Take elements from this stream until the provided future resolves.
1014    ///
1015    /// This function will take elements from the stream until the provided
1016    /// stopping future `fut` resolves. Once the `fut` future becomes ready,
1017    /// this stream combinator will always return that the stream is done.
1018    ///
1019    /// The stopping future may return any type. Once the stream is stopped
1020    /// the result of the stopping future may be accessed with `TakeUntil::take_result()`.
1021    /// The stream may also be resumed with `TakeUntil::take_future()`.
1022    /// See the documentation of [`TakeUntil`] for more information.
1023    ///
1024    /// # Examples
1025    ///
1026    /// ```
1027    /// # futures::executor::block_on(async {
1028    /// use futures::future;
1029    /// use futures::stream::{self, StreamExt};
1030    /// use futures::task::Poll;
1031    ///
1032    /// let stream = stream::iter(1..=10);
1033    ///
1034    /// let mut i = 0;
1035    /// let stop_fut = future::poll_fn(|_cx| {
1036    ///     i += 1;
1037    ///     if i <= 5 {
1038    ///         Poll::Pending
1039    ///     } else {
1040    ///         Poll::Ready(())
1041    ///     }
1042    /// });
1043    ///
1044    /// let stream = stream.take_until(stop_fut);
1045    ///
1046    /// assert_eq!(vec![1, 2, 3, 4, 5], stream.collect::<Vec<_>>().await);
1047    /// # });
1048    /// ```
1049    fn take_until<Fut>(self, fut: Fut) -> TakeUntil<Self, Fut>
1050    where
1051        Fut: Future,
1052        Self: Sized,
1053    {
1054        assert_stream::<Self::Item, _>(TakeUntil::new(self, fut))
1055    }
1056
1057    /// Runs this stream to completion, executing the provided asynchronous
1058    /// closure for each element on the stream.
1059    ///
1060    /// The closure provided will be called for each item this stream produces,
1061    /// yielding a future. That future will then be executed to completion
1062    /// before moving on to the next item.
1063    ///
1064    /// The returned value is a `Future` where the `Output` type is `()`; it is
1065    /// executed entirely for its side effects.
1066    ///
1067    /// To process each item in the stream and produce another stream instead
1068    /// of a single future, use `then` instead.
1069    ///
1070    /// # Examples
1071    ///
1072    /// ```
1073    /// # futures::executor::block_on(async {
1074    /// use futures::future;
1075    /// use futures::stream::{self, StreamExt};
1076    ///
1077    /// let mut x = 0;
1078    ///
1079    /// {
1080    ///     let fut = stream::repeat(1).take(3).for_each(|item| {
1081    ///         x += item;
1082    ///         future::ready(())
1083    ///     });
1084    ///     fut.await;
1085    /// }
1086    ///
1087    /// assert_eq!(x, 3);
1088    /// # });
1089    /// ```
1090    fn for_each<Fut, F>(self, f: F) -> ForEach<Self, Fut, F>
1091    where
1092        F: FnMut(Self::Item) -> Fut,
1093        Fut: Future<Output = ()>,
1094        Self: Sized,
1095    {
1096        assert_future::<(), _>(ForEach::new(self, f))
1097    }
1098
1099    /// Runs this stream to completion, executing the provided asynchronous
1100    /// closure for each element on the stream concurrently as elements become
1101    /// available.
1102    ///
1103    /// This is similar to [`StreamExt::for_each`], but the futures
1104    /// produced by the closure are run concurrently (but not in parallel--
1105    /// this combinator does not introduce any threads).
1106    ///
1107    /// The closure provided will be called for each item this stream produces,
1108    /// yielding a future. That future will then be executed to completion
1109    /// concurrently with the other futures produced by the closure.
1110    ///
1111    /// The first argument is an optional limit on the number of concurrent
1112    /// futures. If this limit is not `None`, no more than `limit` futures
1113    /// will be run concurrently. The `limit` argument is of type
1114    /// `Into<Option<usize>>`, and so can be provided as either `None`,
1115    /// `Some(10)`, or just `10`. Note: a limit of zero is interpreted as
1116    /// no limit at all, and will have the same result as passing in `None`.
1117    ///
1118    /// This method is only available when the `std` or `alloc` feature of this
1119    /// library is activated, and it is activated by default.
1120    ///
1121    /// # Examples
1122    ///
1123    /// ```
1124    /// # futures::executor::block_on(async {
1125    /// use futures::channel::oneshot;
1126    /// use futures::stream::{self, StreamExt};
1127    ///
1128    /// let (tx1, rx1) = oneshot::channel();
1129    /// let (tx2, rx2) = oneshot::channel();
1130    /// let (tx3, rx3) = oneshot::channel();
1131    ///
1132    /// let fut = stream::iter(vec![rx1, rx2, rx3]).for_each_concurrent(
1133    ///     /* limit */ 2,
1134    ///     |rx| async move {
1135    ///         rx.await.unwrap();
1136    ///     }
1137    /// );
1138    /// tx1.send(()).unwrap();
1139    /// tx2.send(()).unwrap();
1140    /// tx3.send(()).unwrap();
1141    /// fut.await;
1142    /// # })
1143    /// ```
1144    #[cfg(target_has_atomic = "ptr")]
1145    #[cfg(feature = "alloc")]
1146    fn for_each_concurrent<Fut, F>(
1147        self,
1148        limit: impl Into<Option<usize>>,
1149        f: F,
1150    ) -> ForEachConcurrent<Self, Fut, F>
1151    where
1152        F: FnMut(Self::Item) -> Fut,
1153        Fut: Future<Output = ()>,
1154        Self: Sized,
1155    {
1156        assert_future::<(), _>(ForEachConcurrent::new(self, limit.into(), f))
1157    }
1158
1159    /// Creates a new stream of at most `n` items of the underlying stream.
1160    ///
1161    /// Once `n` items have been yielded from this stream then it will always
1162    /// return that the stream is done.
1163    ///
1164    /// # Examples
1165    ///
1166    /// ```
1167    /// # futures::executor::block_on(async {
1168    /// use futures::stream::{self, StreamExt};
1169    ///
1170    /// let stream = stream::iter(1..=10).take(3);
1171    ///
1172    /// assert_eq!(vec![1, 2, 3], stream.collect::<Vec<_>>().await);
1173    /// # });
1174    /// ```
1175    fn take(self, n: usize) -> Take<Self>
1176    where
1177        Self: Sized,
1178    {
1179        assert_stream::<Self::Item, _>(Take::new(self, n))
1180    }
1181
1182    /// Creates a new stream which skips `n` items of the underlying stream.
1183    ///
1184    /// Once `n` items have been skipped from this stream then it will always
1185    /// return the remaining items on this stream.
1186    ///
1187    /// # Examples
1188    ///
1189    /// ```
1190    /// # futures::executor::block_on(async {
1191    /// use futures::stream::{self, StreamExt};
1192    ///
1193    /// let stream = stream::iter(1..=10).skip(5);
1194    ///
1195    /// assert_eq!(vec![6, 7, 8, 9, 10], stream.collect::<Vec<_>>().await);
1196    /// # });
1197    /// ```
1198    fn skip(self, n: usize) -> Skip<Self>
1199    where
1200        Self: Sized,
1201    {
1202        assert_stream::<Self::Item, _>(Skip::new(self, n))
1203    }
1204
1205    /// Fuse a stream such that [`poll_next`](Stream::poll_next) will never
1206    /// again be called once it has finished. This method can be used to turn
1207    /// any `Stream` into a `FusedStream`.
1208    ///
1209    /// Normally, once a stream has returned [`None`] from
1210    /// [`poll_next`](Stream::poll_next) any further calls could exhibit bad
1211    /// behavior such as block forever, panic, never return, etc. If it is known
1212    /// that [`poll_next`](Stream::poll_next) may be called after stream
1213    /// has already finished, then this method can be used to ensure that it has
1214    /// defined semantics.
1215    ///
1216    /// The [`poll_next`](Stream::poll_next) method of a `fuse`d stream
1217    /// is guaranteed to return [`None`] after the underlying stream has
1218    /// finished.
1219    ///
1220    /// # Examples
1221    ///
1222    /// ```
1223    /// use futures::executor::block_on_stream;
1224    /// use futures::stream::{self, StreamExt};
1225    /// use futures::task::Poll;
1226    ///
1227    /// let mut x = 0;
1228    /// let stream = stream::poll_fn(|_| {
1229    ///     x += 1;
1230    ///     match x {
1231    ///         0..=2 => Poll::Ready(Some(x)),
1232    ///         3 => Poll::Ready(None),
1233    ///         _ => panic!("should not happen")
1234    ///     }
1235    /// }).fuse();
1236    ///
1237    /// let mut iter = block_on_stream(stream);
1238    /// assert_eq!(Some(1), iter.next());
1239    /// assert_eq!(Some(2), iter.next());
1240    /// assert_eq!(None, iter.next());
1241    /// assert_eq!(None, iter.next());
1242    /// // ...
1243    /// ```
1244    fn fuse(self) -> Fuse<Self>
1245    where
1246        Self: Sized,
1247    {
1248        assert_stream::<Self::Item, _>(Fuse::new(self))
1249    }
1250
1251    /// Borrows a stream, rather than consuming it.
1252    ///
1253    /// This is useful to allow applying stream adaptors while still retaining
1254    /// ownership of the original stream.
1255    ///
1256    /// # Examples
1257    ///
1258    /// ```
1259    /// # futures::executor::block_on(async {
1260    /// use futures::stream::{self, StreamExt};
1261    ///
1262    /// let mut stream = stream::iter(1..5);
1263    ///
1264    /// let sum = stream.by_ref()
1265    ///                 .take(2)
1266    ///                 .fold(0, |a, b| async move { a + b })
1267    ///                 .await;
1268    /// assert_eq!(sum, 3);
1269    ///
1270    /// // You can use the stream again
1271    /// let sum = stream.take(2)
1272    ///                 .fold(0, |a, b| async move { a + b })
1273    ///                 .await;
1274    /// assert_eq!(sum, 7);
1275    /// # });
1276    /// ```
1277    fn by_ref(&mut self) -> &mut Self {
1278        self
1279    }
1280
1281    /// Catches unwinding panics while polling the stream.
1282    ///
1283    /// Caught panic (if any) will be the last element of the resulting stream.
1284    ///
1285    /// In general, panics within a stream can propagate all the way out to the
1286    /// task level. This combinator makes it possible to halt unwinding within
1287    /// the stream itself. It's most commonly used within task executors. This
1288    /// method should not be used for error handling.
1289    ///
1290    /// Note that this method requires the `UnwindSafe` bound from the standard
1291    /// library. This isn't always applied automatically, and the standard
1292    /// library provides an `AssertUnwindSafe` wrapper type to apply it
1293    /// after-the fact. To assist using this method, the [`Stream`] trait is
1294    /// also implemented for `AssertUnwindSafe<St>` where `St` implements
1295    /// [`Stream`].
1296    ///
1297    /// This method is only available when the `std` feature of this
1298    /// library is activated, and it is activated by default.
1299    ///
1300    /// # Examples
1301    ///
1302    /// ```
1303    /// # futures::executor::block_on(async {
1304    /// use futures::stream::{self, StreamExt};
1305    ///
1306    /// let stream = stream::iter(vec![Some(10), None, Some(11)]);
1307    /// // Panic on second element
1308    /// let stream_panicking = stream.map(|o| o.unwrap());
1309    /// // Collect all the results
1310    /// let stream = stream_panicking.catch_unwind();
1311    ///
1312    /// let results: Vec<Result<i32, _>> = stream.collect().await;
1313    /// match results[0] {
1314    ///     Ok(10) => {}
1315    ///     _ => panic!("unexpected result!"),
1316    /// }
1317    /// assert!(results[1].is_err());
1318    /// assert_eq!(results.len(), 2);
1319    /// # });
1320    /// ```
1321    #[cfg(feature = "std")]
1322    fn catch_unwind(self) -> CatchUnwind<Self>
1323    where
1324        Self: Sized + std::panic::UnwindSafe,
1325    {
1326        assert_stream(CatchUnwind::new(self))
1327    }
1328
1329    /// Wrap the stream in a Box, pinning it.
1330    ///
1331    /// This method is only available when the `std` or `alloc` feature of this
1332    /// library is activated, and it is activated by default.
1333    #[cfg(feature = "alloc")]
1334    fn boxed<'a>(self) -> BoxStream<'a, Self::Item>
1335    where
1336        Self: Sized + Send + 'a,
1337    {
1338        assert_stream::<Self::Item, _>(Box::pin(self))
1339    }
1340
1341    /// Wrap the stream in a Box, pinning it.
1342    ///
1343    /// Similar to `boxed`, but without the `Send` requirement.
1344    ///
1345    /// This method is only available when the `std` or `alloc` feature of this
1346    /// library is activated, and it is activated by default.
1347    #[cfg(feature = "alloc")]
1348    fn boxed_local<'a>(self) -> LocalBoxStream<'a, Self::Item>
1349    where
1350        Self: Sized + 'a,
1351    {
1352        assert_stream::<Self::Item, _>(Box::pin(self))
1353    }
1354
1355    /// An adaptor for creating a buffered list of pending futures.
1356    ///
1357    /// If this stream's item can be converted into a future, then this adaptor
1358    /// will buffer up to at most `n` futures and then return the outputs in the
1359    /// same order as the underlying stream. No more than `n` futures will be
1360    /// buffered at any point in time, and less than `n` may also be buffered
1361    /// depending on the state of each future.
1362    ///
1363    /// The returned stream will be a stream of each future's output.
1364    ///
1365    /// This method is only available when the `std` or `alloc` feature of this
1366    /// library is activated, and it is activated by default.
1367    #[cfg(target_has_atomic = "ptr")]
1368    #[cfg(feature = "alloc")]
1369    fn buffered(self, n: usize) -> Buffered<Self>
1370    where
1371        Self::Item: Future,
1372        Self: Sized,
1373    {
1374        assert_stream::<<Self::Item as Future>::Output, _>(Buffered::new(self, n))
1375    }
1376
1377    /// An adaptor for creating a buffered list of pending futures (unordered).
1378    ///
1379    /// If this stream's item can be converted into a future, then this adaptor
1380    /// will buffer up to `n` futures and then return the outputs in the order
1381    /// in which they complete. No more than `n` futures will be buffered at
1382    /// any point in time, and less than `n` may also be buffered depending on
1383    /// the state of each future.
1384    ///
1385    /// The returned stream will be a stream of each future's output.
1386    ///
1387    /// This method is only available when the `std` or `alloc` feature of this
1388    /// library is activated, and it is activated by default.
1389    ///
1390    /// # Examples
1391    ///
1392    /// ```
1393    /// # futures::executor::block_on(async {
1394    /// use futures::channel::oneshot;
1395    /// use futures::stream::{self, StreamExt};
1396    ///
1397    /// let (send_one, recv_one) = oneshot::channel();
1398    /// let (send_two, recv_two) = oneshot::channel();
1399    ///
1400    /// let stream_of_futures = stream::iter(vec![recv_one, recv_two]);
1401    /// let mut buffered = stream_of_futures.buffer_unordered(10);
1402    ///
1403    /// send_two.send(2i32)?;
1404    /// assert_eq!(buffered.next().await, Some(Ok(2i32)));
1405    ///
1406    /// send_one.send(1i32)?;
1407    /// assert_eq!(buffered.next().await, Some(Ok(1i32)));
1408    ///
1409    /// assert_eq!(buffered.next().await, None);
1410    /// # Ok::<(), i32>(()) }).unwrap();
1411    /// ```
1412    #[cfg(target_has_atomic = "ptr")]
1413    #[cfg(feature = "alloc")]
1414    fn buffer_unordered(self, n: usize) -> BufferUnordered<Self>
1415    where
1416        Self::Item: Future,
1417        Self: Sized,
1418    {
1419        assert_stream::<<Self::Item as Future>::Output, _>(BufferUnordered::new(self, n))
1420    }
1421
1422    /// An adapter for zipping two streams together.
1423    ///
1424    /// The zipped stream waits for both streams to produce an item, and then
1425    /// returns that pair. If either stream ends then the zipped stream will
1426    /// also end.
1427    ///
1428    /// # Examples
1429    ///
1430    /// ```
1431    /// # futures::executor::block_on(async {
1432    /// use futures::stream::{self, StreamExt};
1433    ///
1434    /// let stream1 = stream::iter(1..=3);
1435    /// let stream2 = stream::iter(5..=10);
1436    ///
1437    /// let vec = stream1.zip(stream2)
1438    ///                  .collect::<Vec<_>>()
1439    ///                  .await;
1440    /// assert_eq!(vec![(1, 5), (2, 6), (3, 7)], vec);
1441    /// # });
1442    /// ```
1443    ///
1444    fn zip<St>(self, other: St) -> Zip<Self, St>
1445    where
1446        St: Stream,
1447        Self: Sized,
1448    {
1449        assert_stream::<(Self::Item, St::Item), _>(Zip::new(self, other))
1450    }
1451
1452    /// Adapter for chaining two streams.
1453    ///
1454    /// The resulting stream emits elements from the first stream, and when
1455    /// first stream reaches the end, emits the elements from the second stream.
1456    ///
1457    /// ```
1458    /// # futures::executor::block_on(async {
1459    /// use futures::stream::{self, StreamExt};
1460    ///
1461    /// let stream1 = stream::iter(vec![Ok(10), Err(false)]);
1462    /// let stream2 = stream::iter(vec![Err(true), Ok(20)]);
1463    ///
1464    /// let stream = stream1.chain(stream2);
1465    ///
1466    /// let result: Vec<_> = stream.collect().await;
1467    /// assert_eq!(result, vec![
1468    ///     Ok(10),
1469    ///     Err(false),
1470    ///     Err(true),
1471    ///     Ok(20),
1472    /// ]);
1473    /// # });
1474    /// ```
1475    fn chain<St>(self, other: St) -> Chain<Self, St>
1476    where
1477        St: Stream<Item = Self::Item>,
1478        Self: Sized,
1479    {
1480        assert_stream::<Self::Item, _>(Chain::new(self, other))
1481    }
1482
1483    /// Creates a new stream which exposes a `peek` method.
1484    ///
1485    /// Calling `peek` returns a reference to the next item in the stream.
1486    fn peekable(self) -> Peekable<Self>
1487    where
1488        Self: Sized,
1489    {
1490        assert_stream::<Self::Item, _>(Peekable::new(self))
1491    }
1492
1493    /// An adaptor for chunking up items of the stream inside a vector.
1494    ///
1495    /// This combinator will attempt to pull items from this stream and buffer
1496    /// them into a local vector. At most `capacity` items will get buffered
1497    /// before they're yielded from the returned stream.
1498    ///
1499    /// Note that the vectors returned from this iterator may not always have
1500    /// `capacity` elements. If the underlying stream ended and only a partial
1501    /// vector was created, it'll be returned. Additionally if an error happens
1502    /// from the underlying stream then the currently buffered items will be
1503    /// yielded.
1504    ///
1505    /// This method is only available when the `std` or `alloc` feature of this
1506    /// library is activated, and it is activated by default.
1507    ///
1508    /// # Panics
1509    ///
1510    /// This method will panic if `capacity` is zero.
1511    #[cfg(feature = "alloc")]
1512    fn chunks(self, capacity: usize) -> Chunks<Self>
1513    where
1514        Self: Sized,
1515    {
1516        assert_stream::<Vec<Self::Item>, _>(Chunks::new(self, capacity))
1517    }
1518
1519    /// An adaptor for chunking up ready items of the stream inside a vector.
1520    ///
1521    /// This combinator will attempt to pull ready items from this stream and
1522    /// buffer them into a local vector. At most `capacity` items will get
1523    /// buffered before they're yielded from the returned stream. If underlying
1524    /// stream returns `Poll::Pending`, and collected chunk is not empty, it will
1525    /// be immediately returned.
1526    ///
1527    /// If the underlying stream ended and only a partial vector was created,
1528    /// it will be returned.
1529    ///
1530    /// This method is only available when the `std` or `alloc` feature of this
1531    /// library is activated, and it is activated by default.
1532    ///
1533    /// # Panics
1534    ///
1535    /// This method will panic if `capacity` is zero.
1536    #[cfg(feature = "alloc")]
1537    fn ready_chunks(self, capacity: usize) -> ReadyChunks<Self>
1538    where
1539        Self: Sized,
1540    {
1541        assert_stream::<Vec<Self::Item>, _>(ReadyChunks::new(self, capacity))
1542    }
1543
1544    /// A future that completes after the given stream has been fully processed
1545    /// into the sink and the sink has been flushed and closed.
1546    ///
1547    /// This future will drive the stream to keep producing items until it is
1548    /// exhausted, sending each item to the sink. It will complete once the
1549    /// stream is exhausted, the sink has received and flushed all items, and
1550    /// the sink is closed. Note that neither the original stream nor provided
1551    /// sink will be output by this future. Pass the sink by `Pin<&mut S>`
1552    /// (for example, via `forward(&mut sink)` inside an `async` fn/block) in
1553    /// order to preserve access to the `Sink`. If the stream produces an error,
1554    /// that error will be returned by this future without flushing/closing the sink.
1555    #[cfg(feature = "sink")]
1556    #[cfg_attr(docsrs, doc(cfg(feature = "sink")))]
1557    fn forward<S>(self, sink: S) -> Forward<Self, S>
1558    where
1559        S: Sink<Self::Ok, Error = Self::Error>,
1560        Self: TryStream + Sized,
1561        // Self: TryStream + Sized + Stream<Item = Result<<Self as TryStream>::Ok, <Self as TryStream>::Error>>,
1562    {
1563        // TODO: type mismatch resolving `<Self as futures_core::Stream>::Item == std::result::Result<<Self as futures_core::TryStream>::Ok, <Self as futures_core::TryStream>::Error>`
1564        // assert_future::<Result<(), Self::Error>, _>(Forward::new(self, sink))
1565        Forward::new(self, sink)
1566    }
1567
1568    /// Splits this `Stream + Sink` object into separate `Sink` and `Stream`
1569    /// objects.
1570    ///
1571    /// This can be useful when you want to split ownership between tasks, or
1572    /// allow direct interaction between the two objects (e.g. via
1573    /// `Sink::send_all`).
1574    ///
1575    /// This method is only available when the `std` or `alloc` feature of this
1576    /// library is activated, and it is activated by default.
1577    #[cfg(feature = "sink")]
1578    #[cfg_attr(docsrs, doc(cfg(feature = "sink")))]
1579    #[cfg(target_has_atomic = "ptr")]
1580    #[cfg(feature = "alloc")]
1581    fn split<Item>(self) -> (SplitSink<Self, Item>, SplitStream<Self>)
1582    where
1583        Self: Sink<Item> + Sized,
1584    {
1585        let (sink, stream) = split::split(self);
1586        (
1587            crate::sink::assert_sink::<Item, Self::Error, _>(sink),
1588            assert_stream::<Self::Item, _>(stream),
1589        )
1590    }
1591
1592    /// Do something with each item of this stream, afterwards passing it on.
1593    ///
1594    /// This is similar to the `Iterator::inspect` method in the standard
1595    /// library where it allows easily inspecting each value as it passes
1596    /// through the stream, for example to debug what's going on.
1597    fn inspect<F>(self, f: F) -> Inspect<Self, F>
1598    where
1599        F: FnMut(&Self::Item),
1600        Self: Sized,
1601    {
1602        assert_stream::<Self::Item, _>(Inspect::new(self, f))
1603    }
1604
1605    /// Wrap this stream in an `Either` stream, making it the left-hand variant
1606    /// of that `Either`.
1607    ///
1608    /// This can be used in combination with the `right_stream` method to write `if`
1609    /// statements that evaluate to different streams in different branches.
1610    fn left_stream<B>(self) -> Either<Self, B>
1611    where
1612        B: Stream<Item = Self::Item>,
1613        Self: Sized,
1614    {
1615        assert_stream::<Self::Item, _>(Either::Left(self))
1616    }
1617
1618    /// Wrap this stream in an `Either` stream, making it the right-hand variant
1619    /// of that `Either`.
1620    ///
1621    /// This can be used in combination with the `left_stream` method to write `if`
1622    /// statements that evaluate to different streams in different branches.
1623    fn right_stream<B>(self) -> Either<B, Self>
1624    where
1625        B: Stream<Item = Self::Item>,
1626        Self: Sized,
1627    {
1628        assert_stream::<Self::Item, _>(Either::Right(self))
1629    }
1630
1631    /// A convenience method for calling [`Stream::poll_next`] on [`Unpin`]
1632    /// stream types.
1633    fn poll_next_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>
1634    where
1635        Self: Unpin,
1636    {
1637        Pin::new(self).poll_next(cx)
1638    }
1639
1640    /// Returns a [`Future`] that resolves when the next item in this stream is
1641    /// ready.
1642    ///
1643    /// This is similar to the [`next`][StreamExt::next] method, but it won't
1644    /// resolve to [`None`] if used on an empty [`Stream`]. Instead, the
1645    /// returned future type will return `true` from
1646    /// [`FusedFuture::is_terminated`][] when the [`Stream`] is empty, allowing
1647    /// [`select_next_some`][StreamExt::select_next_some] to be easily used with
1648    /// the [`select!`] macro.
1649    ///
1650    /// If the future is polled after this [`Stream`] is empty it will panic.
1651    /// Using the future with a [`FusedFuture`][]-aware primitive like the
1652    /// [`select!`] macro will prevent this.
1653    ///
1654    /// [`FusedFuture`]: futures_core::future::FusedFuture
1655    /// [`FusedFuture::is_terminated`]: futures_core::future::FusedFuture::is_terminated
1656    ///
1657    /// # Examples
1658    ///
1659    /// ```
1660    /// # futures::executor::block_on(async {
1661    /// use futures::{future, select};
1662    /// use futures::stream::{StreamExt, FuturesUnordered};
1663    ///
1664    /// let mut fut = future::ready(1);
1665    /// let mut async_tasks = FuturesUnordered::new();
1666    /// let mut total = 0;
1667    /// loop {
1668    ///     select! {
1669    ///         num = fut => {
1670    ///             // First, the `ready` future completes.
1671    ///             total += num;
1672    ///             // Then we spawn a new task onto `async_tasks`,
1673    ///             async_tasks.push(async { 5 });
1674    ///         },
1675    ///         // On the next iteration of the loop, the task we spawned
1676    ///         // completes.
1677    ///         num = async_tasks.select_next_some() => {
1678    ///             total += num;
1679    ///         }
1680    ///         // Finally, both the `ready` future and `async_tasks` have
1681    ///         // finished, so we enter the `complete` branch.
1682    ///         complete => break,
1683    ///     }
1684    /// }
1685    /// assert_eq!(total, 6);
1686    /// # });
1687    /// ```
1688    ///
1689    /// [`select!`]: crate::select
1690    fn select_next_some(&mut self) -> SelectNextSome<'_, Self>
1691    where
1692        Self: Unpin + FusedStream,
1693    {
1694        assert_future::<Self::Item, _>(SelectNextSome::new(self))
1695    }
1696}