Skip to main content

futures_lite/
stream.rs

1//! Combinators for the [`Stream`] trait.
2//!
3//! # Examples
4//!
5//! ```
6//! use futures_lite::stream::{self, StreamExt};
7//!
8//! # spin_on::spin_on(async {
9//! let mut s = stream::iter(vec![1, 2, 3]);
10//!
11//! assert_eq!(s.next().await, Some(1));
12//! assert_eq!(s.next().await, Some(2));
13//! assert_eq!(s.next().await, Some(3));
14//! assert_eq!(s.next().await, None);
15//! # });
16//! ```
17
18#[doc(no_inline)]
19pub use futures_core::stream::Stream;
20
21#[cfg(feature = "alloc")]
22use alloc::boxed::Box;
23
24use core::fmt;
25use core::future::Future;
26use core::marker::PhantomData;
27use core::mem;
28use core::pin::Pin;
29use core::task::{Context, Poll};
30
31#[cfg(feature = "race")]
32use fastrand::Rng;
33
34use pin_project_lite::pin_project;
35
36use crate::ready;
37
38/// Converts a stream into a blocking iterator.
39///
40/// # Examples
41///
42/// ```
43/// use futures_lite::{pin, stream};
44///
45/// let stream = stream::once(7);
46/// pin!(stream);
47///
48/// let mut iter = stream::block_on(stream);
49/// assert_eq!(iter.next(), Some(7));
50/// assert_eq!(iter.next(), None);
51/// ```
52#[cfg(feature = "std")]
53pub fn block_on<S: Stream + Unpin>(stream: S) -> BlockOn<S> {
54    BlockOn(stream)
55}
56
57/// Iterator for the [`block_on()`] function.
58#[derive(Debug)]
59pub struct BlockOn<S>(S);
60
61#[cfg(feature = "std")]
62impl<S: Stream + Unpin> Iterator for BlockOn<S> {
63    type Item = S::Item;
64
65    fn next(&mut self) -> Option<Self::Item> {
66        crate::future::block_on(self.0.next())
67    }
68
69    fn size_hint(&self) -> (usize, Option<usize>) {
70        self.0.size_hint()
71    }
72
73    fn count(self) -> usize {
74        crate::future::block_on(self.0.count())
75    }
76
77    fn last(self) -> Option<Self::Item> {
78        crate::future::block_on(self.0.last())
79    }
80
81    fn nth(&mut self, n: usize) -> Option<Self::Item> {
82        crate::future::block_on(self.0.nth(n))
83    }
84
85    fn fold<B, F>(self, init: B, f: F) -> B
86    where
87        F: FnMut(B, Self::Item) -> B,
88    {
89        crate::future::block_on(self.0.fold(init, f))
90    }
91
92    fn for_each<F>(self, f: F) -> F::Output
93    where
94        F: FnMut(Self::Item),
95    {
96        crate::future::block_on(self.0.for_each(f))
97    }
98
99    fn all<F>(&mut self, f: F) -> bool
100    where
101        F: FnMut(Self::Item) -> bool,
102    {
103        crate::future::block_on(self.0.all(f))
104    }
105
106    fn any<F>(&mut self, f: F) -> bool
107    where
108        F: FnMut(Self::Item) -> bool,
109    {
110        crate::future::block_on(self.0.any(f))
111    }
112
113    fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
114    where
115        P: FnMut(&Self::Item) -> bool,
116    {
117        crate::future::block_on(self.0.find(predicate))
118    }
119
120    fn find_map<B, F>(&mut self, f: F) -> Option<B>
121    where
122        F: FnMut(Self::Item) -> Option<B>,
123    {
124        crate::future::block_on(self.0.find_map(f))
125    }
126
127    fn position<P>(&mut self, predicate: P) -> Option<usize>
128    where
129        P: FnMut(Self::Item) -> bool,
130    {
131        crate::future::block_on(self.0.position(predicate))
132    }
133}
134
135/// Creates an empty stream.
136///
137/// # Examples
138///
139/// ```
140/// use futures_lite::stream::{self, StreamExt};
141///
142/// # spin_on::spin_on(async {
143/// let mut s = stream::empty::<i32>();
144/// assert_eq!(s.next().await, None);
145/// # })
146/// ```
147pub fn empty<T>() -> Empty<T> {
148    Empty {
149        _marker: PhantomData,
150    }
151}
152
153/// Stream for the [`empty()`] function.
154#[derive(Clone, Debug)]
155#[must_use = "streams do nothing unless polled"]
156pub struct Empty<T> {
157    _marker: PhantomData<T>,
158}
159
160impl<T> Unpin for Empty<T> {}
161
162impl<T> Stream for Empty<T> {
163    type Item = T;
164
165    fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
166        Poll::Ready(None)
167    }
168
169    fn size_hint(&self) -> (usize, Option<usize>) {
170        (0, Some(0))
171    }
172}
173
174/// Creates a stream from an iterator.
175///
176/// # Examples
177///
178/// ```
179/// use futures_lite::stream::{self, StreamExt};
180///
181/// # spin_on::spin_on(async {
182/// let mut s = stream::iter(vec![1, 2]);
183///
184/// assert_eq!(s.next().await, Some(1));
185/// assert_eq!(s.next().await, Some(2));
186/// assert_eq!(s.next().await, None);
187/// # })
188/// ```
189pub fn iter<I: IntoIterator>(iter: I) -> Iter<I::IntoIter> {
190    Iter {
191        iter: iter.into_iter(),
192    }
193}
194
195/// Stream for the [`iter()`] function.
196#[derive(Clone, Debug)]
197#[must_use = "streams do nothing unless polled"]
198pub struct Iter<I> {
199    iter: I,
200}
201
202impl<I> Unpin for Iter<I> {}
203
204impl<I: Iterator> Stream for Iter<I> {
205    type Item = I::Item;
206
207    fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
208        Poll::Ready(self.iter.next())
209    }
210
211    fn size_hint(&self) -> (usize, Option<usize>) {
212        self.iter.size_hint()
213    }
214}
215
216/// Creates a stream that yields a single item.
217///
218/// # Examples
219///
220/// ```
221/// use futures_lite::stream::{self, StreamExt};
222///
223/// # spin_on::spin_on(async {
224/// let mut s = stream::once(7);
225///
226/// assert_eq!(s.next().await, Some(7));
227/// assert_eq!(s.next().await, None);
228/// # })
229/// ```
230pub fn once<T>(t: T) -> Once<T> {
231    Once { value: Some(t) }
232}
233
234pin_project! {
235    /// Stream for the [`once()`] function.
236    #[derive(Clone, Debug)]
237    #[must_use = "streams do nothing unless polled"]
238    pub struct Once<T> {
239        value: Option<T>,
240    }
241}
242
243impl<T> Stream for Once<T> {
244    type Item = T;
245
246    fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<T>> {
247        Poll::Ready(self.project().value.take())
248    }
249
250    fn size_hint(&self) -> (usize, Option<usize>) {
251        if self.value.is_some() {
252            (1, Some(1))
253        } else {
254            (0, Some(0))
255        }
256    }
257}
258
259/// Creates a stream that is always pending.
260///
261/// # Examples
262///
263/// ```no_run
264/// use futures_lite::stream::{self, StreamExt};
265///
266/// # spin_on::spin_on(async {
267/// let mut s = stream::pending::<i32>();
268/// s.next().await;
269/// unreachable!();
270/// # })
271/// ```
272pub fn pending<T>() -> Pending<T> {
273    Pending {
274        _marker: PhantomData,
275    }
276}
277
278/// Stream for the [`pending()`] function.
279#[derive(Clone, Debug)]
280#[must_use = "streams do nothing unless polled"]
281pub struct Pending<T> {
282    _marker: PhantomData<T>,
283}
284
285impl<T> Unpin for Pending<T> {}
286
287impl<T> Stream for Pending<T> {
288    type Item = T;
289
290    fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<T>> {
291        Poll::Pending
292    }
293
294    fn size_hint(&self) -> (usize, Option<usize>) {
295        (0, Some(0))
296    }
297}
298
299/// Creates a stream from a function returning [`Poll`].
300///
301/// # Examples
302///
303/// ```
304/// use futures_lite::stream::{self, StreamExt};
305/// use std::task::{Context, Poll};
306///
307/// # spin_on::spin_on(async {
308/// fn f(_: &mut Context<'_>) -> Poll<Option<i32>> {
309///     Poll::Ready(Some(7))
310/// }
311///
312/// assert_eq!(stream::poll_fn(f).next().await, Some(7));
313/// # })
314/// ```
315pub fn poll_fn<T, F>(f: F) -> PollFn<F>
316where
317    F: FnMut(&mut Context<'_>) -> Poll<Option<T>>,
318{
319    PollFn { f }
320}
321
322/// Stream for the [`poll_fn()`] function.
323#[derive(Clone)]
324#[must_use = "streams do nothing unless polled"]
325pub struct PollFn<F> {
326    f: F,
327}
328
329impl<F> Unpin for PollFn<F> {}
330
331impl<F> fmt::Debug for PollFn<F> {
332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333        f.debug_struct("PollFn").finish()
334    }
335}
336
337impl<T, F> Stream for PollFn<F>
338where
339    F: FnMut(&mut Context<'_>) -> Poll<Option<T>>,
340{
341    type Item = T;
342
343    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
344        (&mut self.f)(cx)
345    }
346}
347
348/// Creates an infinite stream that yields the same item repeatedly.
349///
350/// # Examples
351///
352/// ```
353/// use futures_lite::stream::{self, StreamExt};
354///
355/// # spin_on::spin_on(async {
356/// let mut s = stream::repeat(7);
357///
358/// assert_eq!(s.next().await, Some(7));
359/// assert_eq!(s.next().await, Some(7));
360/// # })
361/// ```
362pub fn repeat<T: Clone>(item: T) -> Repeat<T> {
363    Repeat { item }
364}
365
366/// Stream for the [`repeat()`] function.
367#[derive(Clone, Debug)]
368#[must_use = "streams do nothing unless polled"]
369pub struct Repeat<T> {
370    item: T,
371}
372
373impl<T> Unpin for Repeat<T> {}
374
375impl<T: Clone> Stream for Repeat<T> {
376    type Item = T;
377
378    fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
379        Poll::Ready(Some(self.item.clone()))
380    }
381
382    fn size_hint(&self) -> (usize, Option<usize>) {
383        (usize::MAX, None)
384    }
385}
386
387/// Creates an infinite stream from a closure that generates items.
388///
389/// # Examples
390///
391/// ```
392/// use futures_lite::stream::{self, StreamExt};
393///
394/// # spin_on::spin_on(async {
395/// let mut s = stream::repeat_with(|| 7);
396///
397/// assert_eq!(s.next().await, Some(7));
398/// assert_eq!(s.next().await, Some(7));
399/// # })
400/// ```
401pub fn repeat_with<T, F>(repeater: F) -> RepeatWith<F>
402where
403    F: FnMut() -> T,
404{
405    RepeatWith { f: repeater }
406}
407
408/// Stream for the [`repeat_with()`] function.
409#[derive(Clone, Debug)]
410#[must_use = "streams do nothing unless polled"]
411pub struct RepeatWith<F> {
412    f: F,
413}
414
415impl<F> Unpin for RepeatWith<F> {}
416
417impl<T, F> Stream for RepeatWith<F>
418where
419    F: FnMut() -> T,
420{
421    type Item = T;
422
423    fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
424        let item = (&mut self.f)();
425        Poll::Ready(Some(item))
426    }
427
428    fn size_hint(&self) -> (usize, Option<usize>) {
429        (usize::MAX, None)
430    }
431}
432
433/// Creates a stream from a seed value and an async closure operating on it.
434///
435/// # Examples
436///
437/// ```
438/// use futures_lite::stream::{self, StreamExt};
439///
440/// # spin_on::spin_on(async {
441/// let s = stream::unfold(0, |mut n| async move {
442///     if n < 2 {
443///         let m = n + 1;
444///         Some((n, m))
445///     } else {
446///         None
447///     }
448/// });
449///
450/// let v: Vec<i32> = s.collect().await;
451/// assert_eq!(v, [0, 1]);
452/// # })
453/// ```
454pub fn unfold<T, F, Fut, Item>(seed: T, f: F) -> Unfold<T, F, Fut>
455where
456    F: FnMut(T) -> Fut,
457    Fut: Future<Output = Option<(Item, T)>>,
458{
459    Unfold {
460        f,
461        state: Some(seed),
462        fut: None,
463    }
464}
465
466pin_project! {
467    /// Stream for the [`unfold()`] function.
468    #[derive(Clone)]
469    #[must_use = "streams do nothing unless polled"]
470    pub struct Unfold<T, F, Fut> {
471        f: F,
472        state: Option<T>,
473        #[pin]
474        fut: Option<Fut>,
475    }
476}
477
478impl<T, F, Fut> fmt::Debug for Unfold<T, F, Fut>
479where
480    T: fmt::Debug,
481    Fut: fmt::Debug,
482{
483    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484        f.debug_struct("Unfold")
485            .field("state", &self.state)
486            .field("fut", &self.fut)
487            .finish()
488    }
489}
490
491impl<T, F, Fut, Item> Stream for Unfold<T, F, Fut>
492where
493    F: FnMut(T) -> Fut,
494    Fut: Future<Output = Option<(Item, T)>>,
495{
496    type Item = Item;
497
498    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
499        let mut this = self.project();
500
501        if let Some(state) = this.state.take() {
502            this.fut.set(Some((this.f)(state)));
503        }
504
505        let step = ready!(this
506            .fut
507            .as_mut()
508            .as_pin_mut()
509            .expect("`Unfold` must not be polled after it returned `Poll::Ready(None)`")
510            .poll(cx));
511        this.fut.set(None);
512
513        if let Some((item, next_state)) = step {
514            *this.state = Some(next_state);
515            Poll::Ready(Some(item))
516        } else {
517            Poll::Ready(None)
518        }
519    }
520}
521
522/// Creates a stream from a seed value and a fallible async closure operating on it.
523///
524/// # Examples
525///
526/// ```
527/// use futures_lite::stream::{self, StreamExt};
528///
529/// # spin_on::spin_on(async {
530/// let s = stream::try_unfold(0, |mut n| async move {
531///     if n < 2 {
532///         let m = n + 1;
533///         Ok(Some((n, m)))
534///     } else {
535///         std::io::Result::Ok(None)
536///     }
537/// });
538///
539/// let v: Vec<i32> = s.try_collect().await?;
540/// assert_eq!(v, [0, 1]);
541/// # std::io::Result::Ok(()) });
542/// ```
543pub fn try_unfold<T, E, F, Fut, Item>(init: T, f: F) -> TryUnfold<T, F, Fut>
544where
545    F: FnMut(T) -> Fut,
546    Fut: Future<Output = Result<Option<(Item, T)>, E>>,
547{
548    TryUnfold {
549        f,
550        state: Some(init),
551        fut: None,
552    }
553}
554
555pin_project! {
556    /// Stream for the [`try_unfold()`] function.
557    #[derive(Clone)]
558    #[must_use = "streams do nothing unless polled"]
559    pub struct TryUnfold<T, F, Fut> {
560        f: F,
561        state: Option<T>,
562        #[pin]
563        fut: Option<Fut>,
564    }
565}
566
567impl<T, F, Fut> fmt::Debug for TryUnfold<T, F, Fut>
568where
569    T: fmt::Debug,
570    Fut: fmt::Debug,
571{
572    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
573        f.debug_struct("TryUnfold")
574            .field("state", &self.state)
575            .field("fut", &self.fut)
576            .finish()
577    }
578}
579
580impl<T, E, F, Fut, Item> Stream for TryUnfold<T, F, Fut>
581where
582    F: FnMut(T) -> Fut,
583    Fut: Future<Output = Result<Option<(Item, T)>, E>>,
584{
585    type Item = Result<Item, E>;
586
587    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
588        let mut this = self.project();
589
590        if let Some(state) = this.state.take() {
591            this.fut.set(Some((this.f)(state)));
592        }
593
594        match this.fut.as_mut().as_pin_mut() {
595            None => {
596                // The future previously errored
597                Poll::Ready(None)
598            }
599            Some(future) => {
600                let step = ready!(future.poll(cx));
601                this.fut.set(None);
602
603                match step {
604                    Ok(Some((item, next_state))) => {
605                        *this.state = Some(next_state);
606                        Poll::Ready(Some(Ok(item)))
607                    }
608                    Ok(None) => Poll::Ready(None),
609                    Err(e) => Poll::Ready(Some(Err(e))),
610                }
611            }
612        }
613    }
614}
615
616/// Creates a stream that invokes the given future as its first item, and then
617/// produces no more items.
618///
619/// # Example
620///
621/// ```
622/// use futures_lite::{stream, prelude::*};
623///
624/// # spin_on::spin_on(async {
625/// let mut stream = Box::pin(stream::once_future(async { 1 }));
626/// assert_eq!(stream.next().await, Some(1));
627/// assert_eq!(stream.next().await, None);
628/// # });
629/// ```
630pub fn once_future<F: Future>(future: F) -> OnceFuture<F> {
631    OnceFuture {
632        future: Some(future),
633    }
634}
635
636pin_project! {
637    /// Stream for the [`once_future()`] function.
638    #[derive(Debug)]
639    #[must_use = "futures do nothing unless you `.await` or poll them"]
640    pub struct OnceFuture<F> {
641        #[pin]
642        future: Option<F>,
643    }
644}
645
646impl<F: Future> Stream for OnceFuture<F> {
647    type Item = F::Output;
648
649    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
650        let mut this = self.project();
651
652        match this.future.as_mut().as_pin_mut().map(|f| f.poll(cx)) {
653            Some(Poll::Ready(t)) => {
654                this.future.set(None);
655                Poll::Ready(Some(t))
656            }
657            Some(Poll::Pending) => Poll::Pending,
658            None => Poll::Ready(None),
659        }
660    }
661}
662
663/// Take elements from this stream until the provided future resolves.
664///
665/// This function will take elements from the stream until the provided
666/// stopping future `fut` resolves. Once the `fut` future becomes ready,
667/// this stream combinator will always return that the stream is done.
668///
669/// The stopping future may return any type. Once the stream is stopped
670/// the result of the stopping future may be accessed with `StopAfterFuture::take_result()`.
671/// The stream may also be resumed with `StopAfterFuture::take_future()`.
672/// See the documentation of [`StopAfterFuture`] for more information.
673///
674/// ```
675/// use futures_lite::stream::{self, StreamExt, stop_after_future};
676/// use futures_lite::future;
677/// use std::task::Poll;
678///
679/// let stream = stream::iter(1..=10);
680///
681/// # spin_on::spin_on(async {
682/// let mut i = 0;
683/// let stop_fut = future::poll_fn(|_cx| {
684///     i += 1;
685///     if i <= 5 {
686///         Poll::Pending
687///     } else {
688///         Poll::Ready(())
689///     }
690/// });
691///
692/// let stream = stop_after_future(stream, stop_fut);
693///
694/// assert_eq!(vec![1, 2, 3, 4, 5], stream.collect::<Vec<_>>().await);
695/// # });
696pub fn stop_after_future<S, F>(stream: S, future: F) -> StopAfterFuture<S, F>
697where
698    S: Sized + Stream,
699    F: Future,
700{
701    StopAfterFuture {
702        stream,
703        fut: Some(future),
704        fut_result: None,
705        free: false,
706    }
707}
708
709pin_project! {
710    /// Stream for the [`stop_after_future()`] function.
711    #[derive(Clone, Debug)]
712    #[must_use = "streams do nothing unless polled"]
713    pub struct StopAfterFuture<S: Stream, Fut: Future> {
714        #[pin]
715        stream: S,
716        // Contains the inner Future on start and None once the inner Future is resolved
717        // or taken out by the user.
718        #[pin]
719        fut: Option<Fut>,
720        // Contains fut's return value once fut is resolved
721        fut_result: Option<Fut::Output>,
722        // Whether the future was taken out by the user.
723        free: bool,
724    }
725}
726
727impl<St, Fut> StopAfterFuture<St, Fut>
728where
729    St: Stream,
730    Fut: Future,
731{
732    /// Extract the stopping future out of the combinator.
733    ///
734    /// The future is returned only if it isn't resolved yet, ie. if the stream isn't stopped yet.
735    /// Taking out the future means the combinator will be yielding
736    /// elements from the wrapped stream without ever stopping it.
737    pub fn take_future(&mut self) -> Option<Fut> {
738        if self.fut.is_some() {
739            self.free = true;
740        }
741
742        self.fut.take()
743    }
744
745    /// Once the stopping future is resolved, this method can be used
746    /// to extract the value returned by the stopping future.
747    ///
748    /// This may be used to retrieve arbitrary data from the stopping
749    /// future, for example a reason why the stream was stopped.
750    ///
751    /// This method will return `None` if the future isn't resolved yet,
752    /// or if the result was already taken out.
753    ///
754    /// # Examples
755    ///
756    /// ```
757    /// # spin_on::spin_on(async {
758    /// use futures_lite::stream::{self, StreamExt, stop_after_future};
759    /// use futures_lite::future;
760    /// use std::task::Poll;
761    ///
762    /// let stream = stream::iter(1..=10);
763    ///
764    /// let mut i = 0;
765    /// let stop_fut = future::poll_fn(|_cx| {
766    ///     i += 1;
767    ///     if i <= 5 {
768    ///         Poll::Pending
769    ///     } else {
770    ///         Poll::Ready("reason")
771    ///     }
772    /// });
773    ///
774    /// let mut stream = stop_after_future(stream, stop_fut);
775    /// let _ = (&mut stream).collect::<Vec<_>>().await;
776    ///
777    /// let result = stream.take_result().unwrap();
778    /// assert_eq!(result, "reason");
779    /// # });
780    /// ```
781    pub fn take_result(&mut self) -> Option<Fut::Output> {
782        self.fut_result.take()
783    }
784
785    /// Whether the stream was stopped yet by the stopping future
786    /// being resolved.
787    pub fn is_stopped(&self) -> bool {
788        !self.free && self.fut.is_none()
789    }
790}
791
792impl<St, Fut> Stream for StopAfterFuture<St, Fut>
793where
794    St: Stream,
795    Fut: Future,
796{
797    type Item = St::Item;
798
799    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<St::Item>> {
800        let mut this = self.project();
801
802        if let Some(f) = this.fut.as_mut().as_pin_mut() {
803            if let Poll::Ready(result) = f.poll(cx) {
804                this.fut.set(None);
805                *this.fut_result = Some(result);
806            }
807        }
808
809        if !*this.free && this.fut.is_none() {
810            // Future resolved, inner stream stopped
811            Poll::Ready(None)
812        } else {
813            // Future either not resolved yet or taken out by the user
814            let item = ready!(this.stream.poll_next(cx));
815            if item.is_none() {
816                this.fut.set(None);
817            }
818            Poll::Ready(item)
819        }
820    }
821
822    fn size_hint(&self) -> (usize, Option<usize>) {
823        if self.is_stopped() {
824            return (0, Some(0));
825        }
826
827        // Original stream can be truncated at any moment, so the lower bound isn't reliable.
828        let (_, upper_bound) = self.stream.size_hint();
829        (0, upper_bound)
830    }
831}
832
833/// Extension trait for [`Stream`].
834pub trait StreamExt: Stream {
835    /// A convenience for calling [`Stream::poll_next()`] on `!`[`Unpin`] types.
836    fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>
837    where
838        Self: Unpin,
839    {
840        Stream::poll_next(Pin::new(self), cx)
841    }
842
843    /// Retrieves the next item in the stream.
844    ///
845    /// Returns [`None`] when iteration is finished. Stream implementations may choose to or not to
846    /// resume iteration after that.
847    ///
848    /// # Examples
849    ///
850    /// ```
851    /// use futures_lite::stream::{self, StreamExt};
852    ///
853    /// # spin_on::spin_on(async {
854    /// let mut s = stream::iter(1..=3);
855    ///
856    /// assert_eq!(s.next().await, Some(1));
857    /// assert_eq!(s.next().await, Some(2));
858    /// assert_eq!(s.next().await, Some(3));
859    /// assert_eq!(s.next().await, None);
860    /// # });
861    /// ```
862    fn next(&mut self) -> NextFuture<'_, Self>
863    where
864        Self: Unpin,
865    {
866        NextFuture { stream: self }
867    }
868
869    /// Retrieves the next item in the stream.
870    ///
871    /// This is similar to the [`next()`][`StreamExt::next()`] method, but returns
872    /// `Result<Option<T>, E>` rather than `Option<Result<T, E>>`.
873    ///
874    /// Note that `s.try_next().await` is equivalent to `s.next().await.transpose()`.
875    ///
876    /// # Examples
877    ///
878    /// ```
879    /// use futures_lite::stream::{self, StreamExt};
880    ///
881    /// # spin_on::spin_on(async {
882    /// let mut s = stream::iter(vec![Ok(1), Ok(2), Err("error")]);
883    ///
884    /// assert_eq!(s.try_next().await, Ok(Some(1)));
885    /// assert_eq!(s.try_next().await, Ok(Some(2)));
886    /// assert_eq!(s.try_next().await, Err("error"));
887    /// assert_eq!(s.try_next().await, Ok(None));
888    /// # });
889    /// ```
890    fn try_next<T, E>(&mut self) -> TryNextFuture<'_, Self>
891    where
892        Self: Stream<Item = Result<T, E>> + Unpin,
893    {
894        TryNextFuture { stream: self }
895    }
896
897    /// Counts the number of items in the stream.
898    ///
899    /// # Examples
900    ///
901    /// ```
902    /// use futures_lite::stream::{self, StreamExt};
903    ///
904    /// # spin_on::spin_on(async {
905    /// let s1 = stream::iter(vec![0]);
906    /// let s2 = stream::iter(vec![1, 2, 3]);
907    ///
908    /// assert_eq!(s1.count().await, 1);
909    /// assert_eq!(s2.count().await, 3);
910    /// # });
911    /// ```
912    fn count(self) -> CountFuture<Self>
913    where
914        Self: Sized,
915    {
916        CountFuture {
917            stream: self,
918            count: 0,
919        }
920    }
921
922    /// Maps items of the stream to new values using a closure.
923    ///
924    /// # Examples
925    ///
926    /// ```
927    /// use futures_lite::stream::{self, StreamExt};
928    ///
929    /// # spin_on::spin_on(async {
930    /// let s = stream::iter(vec![1, 2, 3]);
931    /// let mut s = s.map(|x| 2 * x);
932    ///
933    /// assert_eq!(s.next().await, Some(2));
934    /// assert_eq!(s.next().await, Some(4));
935    /// assert_eq!(s.next().await, Some(6));
936    /// assert_eq!(s.next().await, None);
937    /// # });
938    /// ```
939    fn map<T, F>(self, f: F) -> Map<Self, F>
940    where
941        Self: Sized,
942        F: FnMut(Self::Item) -> T,
943    {
944        Map { stream: self, f }
945    }
946
947    /// Maps items to streams and then concatenates them.
948    ///
949    /// # Examples
950    ///
951    /// ```
952    /// use futures_lite::stream::{self, StreamExt};
953    ///
954    /// # spin_on::spin_on(async {
955    /// let words = stream::iter(vec!["one", "two"]);
956    ///
957    /// let s: String = words
958    ///     .flat_map(|s| stream::iter(s.chars()))
959    ///     .collect()
960    ///     .await;
961    ///
962    /// assert_eq!(s, "onetwo");
963    /// # });
964    /// ```
965    fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
966    where
967        Self: Sized,
968        U: Stream,
969        F: FnMut(Self::Item) -> U,
970    {
971        FlatMap {
972            stream: self.map(f),
973            inner_stream: None,
974        }
975    }
976
977    /// Concatenates inner streams.
978    ///
979    /// # Examples
980    ///
981    /// ```
982    /// use futures_lite::stream::{self, StreamExt};
983    ///
984    /// # spin_on::spin_on(async {
985    /// let s1 = stream::iter(vec![1, 2, 3]);
986    /// let s2 = stream::iter(vec![4, 5]);
987    ///
988    /// let s = stream::iter(vec![s1, s2]);
989    /// let v: Vec<_> = s.flatten().collect().await;
990    /// assert_eq!(v, [1, 2, 3, 4, 5]);
991    /// # });
992    /// ```
993    fn flatten(self) -> Flatten<Self>
994    where
995        Self: Sized,
996        Self::Item: Stream,
997    {
998        Flatten {
999            stream: self,
1000            inner_stream: None,
1001        }
1002    }
1003
1004    /// Maps items of the stream to new values using an async closure.
1005    ///
1006    /// # Examples
1007    ///
1008    /// ```
1009    /// use futures_lite::pin;
1010    /// use futures_lite::stream::{self, StreamExt};
1011    ///
1012    /// # spin_on::spin_on(async {
1013    /// let s = stream::iter(vec![1, 2, 3]);
1014    /// let mut s = s.then(|x| async move { 2 * x });
1015    ///
1016    /// pin!(s);
1017    /// assert_eq!(s.next().await, Some(2));
1018    /// assert_eq!(s.next().await, Some(4));
1019    /// assert_eq!(s.next().await, Some(6));
1020    /// assert_eq!(s.next().await, None);
1021    /// # });
1022    /// ```
1023    fn then<F, Fut>(self, f: F) -> Then<Self, F, Fut>
1024    where
1025        Self: Sized,
1026        F: FnMut(Self::Item) -> Fut,
1027        Fut: Future,
1028    {
1029        Then {
1030            stream: self,
1031            future: None,
1032            f,
1033        }
1034    }
1035
1036    /// Keeps items of the stream for which `predicate` returns `true`.
1037    ///
1038    /// # Examples
1039    ///
1040    /// ```
1041    /// use futures_lite::stream::{self, StreamExt};
1042    ///
1043    /// # spin_on::spin_on(async {
1044    /// let s = stream::iter(vec![1, 2, 3, 4]);
1045    /// let mut s = s.filter(|i| i % 2 == 0);
1046    ///
1047    /// assert_eq!(s.next().await, Some(2));
1048    /// assert_eq!(s.next().await, Some(4));
1049    /// assert_eq!(s.next().await, None);
1050    /// # });
1051    /// ```
1052    fn filter<P>(self, predicate: P) -> Filter<Self, P>
1053    where
1054        Self: Sized,
1055        P: FnMut(&Self::Item) -> bool,
1056    {
1057        Filter {
1058            stream: self,
1059            predicate,
1060        }
1061    }
1062
1063    /// Filters and maps items of the stream using a closure.
1064    ///
1065    /// # Examples
1066    ///
1067    /// ```
1068    /// use futures_lite::stream::{self, StreamExt};
1069    ///
1070    /// # spin_on::spin_on(async {
1071    /// let s = stream::iter(vec!["1", "lol", "3", "NaN", "5"]);
1072    /// let mut s = s.filter_map(|a| a.parse::<u32>().ok());
1073    ///
1074    /// assert_eq!(s.next().await, Some(1));
1075    /// assert_eq!(s.next().await, Some(3));
1076    /// assert_eq!(s.next().await, Some(5));
1077    /// assert_eq!(s.next().await, None);
1078    /// # });
1079    /// ```
1080    fn filter_map<T, F>(self, f: F) -> FilterMap<Self, F>
1081    where
1082        Self: Sized,
1083        F: FnMut(Self::Item) -> Option<T>,
1084    {
1085        FilterMap { stream: self, f }
1086    }
1087
1088    /// Takes only the first `n` items of the stream.
1089    ///
1090    /// # Examples
1091    ///
1092    /// ```
1093    /// use futures_lite::stream::{self, StreamExt};
1094    ///
1095    /// # spin_on::spin_on(async {
1096    /// let mut s = stream::repeat(7).take(2);
1097    ///
1098    /// assert_eq!(s.next().await, Some(7));
1099    /// assert_eq!(s.next().await, Some(7));
1100    /// assert_eq!(s.next().await, None);
1101    /// # });
1102    /// ```
1103    fn take(self, n: usize) -> Take<Self>
1104    where
1105        Self: Sized,
1106    {
1107        Take { stream: self, n }
1108    }
1109
1110    /// Takes items while `predicate` returns `true`.
1111    ///
1112    /// # Examples
1113    ///
1114    /// ```
1115    /// use futures_lite::stream::{self, StreamExt};
1116    ///
1117    /// # spin_on::spin_on(async {
1118    /// let s = stream::iter(vec![1, 2, 3, 4]);
1119    /// let mut s = s.take_while(|x| *x < 3);
1120    ///
1121    /// assert_eq!(s.next().await, Some(1));
1122    /// assert_eq!(s.next().await, Some(2));
1123    /// assert_eq!(s.next().await, None);
1124    /// # });
1125    /// ```
1126    fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1127    where
1128        Self: Sized,
1129        P: FnMut(&Self::Item) -> bool,
1130    {
1131        TakeWhile {
1132            stream: self,
1133            predicate,
1134        }
1135    }
1136
1137    /// Maps items while `predicate` returns [`Some`].
1138    ///
1139    /// This stream is not fused. After the predicate returns [`None`] the stream still
1140    /// contains remaining items that can be obtained by subsequent `next` calls.
1141    /// You can [`fuse`](StreamExt::fuse) the stream if this behavior is undesirable.
1142    ///
1143    /// # Examples
1144    ///
1145    /// ```
1146    /// use futures_lite::stream::{self, StreamExt};
1147    ///
1148    /// # spin_on::spin_on(async {
1149    /// let s = stream::iter(vec![1, 2, 0, 3]);
1150    /// let mut s = s.map_while(|x: u32| x.checked_sub(1));
1151    ///
1152    /// assert_eq!(s.next().await, Some(0));
1153    /// assert_eq!(s.next().await, Some(1));
1154    /// assert_eq!(s.next().await, None);
1155    ///
1156    /// // Continue to iterate the stream.
1157    /// assert_eq!(s.next().await, Some(2));
1158    /// assert_eq!(s.next().await, None);
1159    /// # });
1160    /// ```
1161    fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1162    where
1163        Self: Sized,
1164        P: FnMut(Self::Item) -> Option<B>,
1165    {
1166        MapWhile {
1167            stream: self,
1168            predicate,
1169        }
1170    }
1171
1172    /// Skips the first `n` items of the stream.
1173    ///
1174    /// # Examples
1175    ///
1176    /// ```
1177    /// use futures_lite::stream::{self, StreamExt};
1178    ///
1179    /// # spin_on::spin_on(async {
1180    /// let s = stream::iter(vec![1, 2, 3]);
1181    /// let mut s = s.skip(2);
1182    ///
1183    /// assert_eq!(s.next().await, Some(3));
1184    /// assert_eq!(s.next().await, None);
1185    /// # });
1186    /// ```
1187    fn skip(self, n: usize) -> Skip<Self>
1188    where
1189        Self: Sized,
1190    {
1191        Skip { stream: self, n }
1192    }
1193
1194    /// Skips items while `predicate` returns `true`.
1195    ///
1196    /// # Examples
1197    ///
1198    /// ```
1199    /// use futures_lite::stream::{self, StreamExt};
1200    ///
1201    /// # spin_on::spin_on(async {
1202    /// let s = stream::iter(vec![-1i32, 0, 1]);
1203    /// let mut s = s.skip_while(|x| x.is_negative());
1204    ///
1205    /// assert_eq!(s.next().await, Some(0));
1206    /// assert_eq!(s.next().await, Some(1));
1207    /// assert_eq!(s.next().await, None);
1208    /// # });
1209    /// ```
1210    fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1211    where
1212        Self: Sized,
1213        P: FnMut(&Self::Item) -> bool,
1214    {
1215        SkipWhile {
1216            stream: self,
1217            predicate: Some(predicate),
1218        }
1219    }
1220
1221    /// Yields every `step`th item.
1222    ///
1223    /// # Panics
1224    ///
1225    /// This method will panic if the `step` is 0.
1226    ///
1227    /// # Examples
1228    ///
1229    /// ```
1230    /// use futures_lite::stream::{self, StreamExt};
1231    ///
1232    /// # spin_on::spin_on(async {
1233    /// let s = stream::iter(vec![0, 1, 2, 3, 4]);
1234    /// let mut s = s.step_by(2);
1235    ///
1236    /// assert_eq!(s.next().await, Some(0));
1237    /// assert_eq!(s.next().await, Some(2));
1238    /// assert_eq!(s.next().await, Some(4));
1239    /// assert_eq!(s.next().await, None);
1240    /// # });
1241    /// ```
1242    fn step_by(self, step: usize) -> StepBy<Self>
1243    where
1244        Self: Sized,
1245    {
1246        assert!(step > 0, "`step` must be greater than zero");
1247        StepBy {
1248            stream: self,
1249            step,
1250            i: 0,
1251        }
1252    }
1253
1254    /// Appends another stream to the end of this one.
1255    ///
1256    /// # Examples
1257    ///
1258    /// ```
1259    /// use futures_lite::stream::{self, StreamExt};
1260    ///
1261    /// # spin_on::spin_on(async {
1262    /// let s1 = stream::iter(vec![1, 2]);
1263    /// let s2 = stream::iter(vec![7, 8]);
1264    /// let mut s = s1.chain(s2);
1265    ///
1266    /// assert_eq!(s.next().await, Some(1));
1267    /// assert_eq!(s.next().await, Some(2));
1268    /// assert_eq!(s.next().await, Some(7));
1269    /// assert_eq!(s.next().await, Some(8));
1270    /// assert_eq!(s.next().await, None);
1271    /// # });
1272    /// ```
1273    fn chain<U>(self, other: U) -> Chain<Self, U>
1274    where
1275        Self: Sized,
1276        U: Stream<Item = Self::Item> + Sized,
1277    {
1278        Chain {
1279            first: self.fuse(),
1280            second: other.fuse(),
1281        }
1282    }
1283
1284    /// Clones all items.
1285    ///
1286    /// # Examples
1287    ///
1288    /// ```
1289    /// use futures_lite::stream::{self, StreamExt};
1290    ///
1291    /// # spin_on::spin_on(async {
1292    /// let s = stream::iter(vec![&1, &2]);
1293    /// let mut s = s.cloned();
1294    ///
1295    /// assert_eq!(s.next().await, Some(1));
1296    /// assert_eq!(s.next().await, Some(2));
1297    /// assert_eq!(s.next().await, None);
1298    /// # });
1299    /// ```
1300    fn cloned<'a, T>(self) -> Cloned<Self>
1301    where
1302        Self: Stream<Item = &'a T> + Sized,
1303        T: Clone + 'a,
1304    {
1305        Cloned { stream: self }
1306    }
1307
1308    /// Copies all items.
1309    ///
1310    /// # Examples
1311    ///
1312    /// ```
1313    /// use futures_lite::stream::{self, StreamExt};
1314    ///
1315    /// # spin_on::spin_on(async {
1316    /// let s = stream::iter(vec![&1, &2]);
1317    /// let mut s = s.copied();
1318    ///
1319    /// assert_eq!(s.next().await, Some(1));
1320    /// assert_eq!(s.next().await, Some(2));
1321    /// assert_eq!(s.next().await, None);
1322    /// # });
1323    /// ```
1324    fn copied<'a, T>(self) -> Copied<Self>
1325    where
1326        Self: Stream<Item = &'a T> + Sized,
1327        T: Copy + 'a,
1328    {
1329        Copied { stream: self }
1330    }
1331
1332    /// Collects all items in the stream into a collection.
1333    ///
1334    /// # Examples
1335    ///
1336    /// ```
1337    /// use futures_lite::stream::{self, StreamExt};
1338    ///
1339    /// # spin_on::spin_on(async {
1340    /// let mut s = stream::iter(1..=3);
1341    ///
1342    /// let items: Vec<_> = s.collect().await;
1343    /// assert_eq!(items, [1, 2, 3]);
1344    /// # });
1345    /// ```
1346    fn collect<C>(self) -> CollectFuture<Self, C>
1347    where
1348        Self: Sized,
1349        C: Default + Extend<Self::Item>,
1350    {
1351        CollectFuture {
1352            stream: self,
1353            collection: Default::default(),
1354        }
1355    }
1356
1357    /// Collects all items in the fallible stream into a collection.
1358    ///
1359    /// ```
1360    /// use futures_lite::stream::{self, StreamExt};
1361    ///
1362    /// # spin_on::spin_on(async {
1363    /// let s = stream::iter(vec![Ok(1), Err(2), Ok(3)]);
1364    /// let res: Result<Vec<i32>, i32> = s.try_collect().await;
1365    /// assert_eq!(res, Err(2));
1366    ///
1367    /// let s = stream::iter(vec![Ok(1), Ok(2), Ok(3)]);
1368    /// let res: Result<Vec<i32>, i32> = s.try_collect().await;
1369    /// assert_eq!(res, Ok(vec![1, 2, 3]));
1370    /// # })
1371    /// ```
1372    fn try_collect<T, E, C>(self) -> TryCollectFuture<Self, C>
1373    where
1374        Self: Stream<Item = Result<T, E>> + Sized,
1375        C: Default + Extend<T>,
1376    {
1377        TryCollectFuture {
1378            stream: self,
1379            items: Default::default(),
1380        }
1381    }
1382
1383    /// Partitions items into those for which `predicate` is `true` and those for which it is
1384    /// `false`, and then collects them into two collections.
1385    ///
1386    /// # Examples
1387    ///
1388    /// ```
1389    /// use futures_lite::stream::{self, StreamExt};
1390    ///
1391    /// # spin_on::spin_on(async {
1392    /// let s = stream::iter(vec![1, 2, 3]);
1393    /// let (even, odd): (Vec<_>, Vec<_>) = s.partition(|&n| n % 2 == 0).await;
1394    ///
1395    /// assert_eq!(even, &[2]);
1396    /// assert_eq!(odd, &[1, 3]);
1397    /// # })
1398    /// ```
1399    fn partition<B, P>(self, predicate: P) -> PartitionFuture<Self, P, B>
1400    where
1401        Self: Sized,
1402        B: Default + Extend<Self::Item>,
1403        P: FnMut(&Self::Item) -> bool,
1404    {
1405        PartitionFuture {
1406            stream: self,
1407            predicate,
1408            res: Some(Default::default()),
1409        }
1410    }
1411
1412    /// Accumulates a computation over the stream.
1413    ///
1414    /// The computation begins with the accumulator value set to `init`, and then applies `f` to
1415    /// the accumulator and each item in the stream. The final accumulator value is returned.
1416    ///
1417    /// # Examples
1418    ///
1419    /// ```
1420    /// use futures_lite::stream::{self, StreamExt};
1421    ///
1422    /// # spin_on::spin_on(async {
1423    /// let s = stream::iter(vec![1, 2, 3]);
1424    /// let sum = s.fold(0, |acc, x| acc + x).await;
1425    ///
1426    /// assert_eq!(sum, 6);
1427    /// # })
1428    /// ```
1429    fn fold<T, F>(self, init: T, f: F) -> FoldFuture<Self, F, T>
1430    where
1431        Self: Sized,
1432        F: FnMut(T, Self::Item) -> T,
1433    {
1434        FoldFuture {
1435            stream: self,
1436            f,
1437            acc: Some(init),
1438        }
1439    }
1440
1441    /// Accumulates a fallible computation over the stream.
1442    ///
1443    /// The computation begins with the accumulator value set to `init`, and then applies `f` to
1444    /// the accumulator and each item in the stream. The final accumulator value is returned, or an
1445    /// error if `f` failed the computation.
1446    ///
1447    /// # Examples
1448    ///
1449    /// ```
1450    /// use futures_lite::stream::{self, StreamExt};
1451    ///
1452    /// # spin_on::spin_on(async {
1453    /// let mut s = stream::iter(vec![Ok(1), Ok(2), Ok(3)]);
1454    ///
1455    /// let sum = s.try_fold(0, |acc, v| {
1456    ///     if (acc + v) % 2 == 1 {
1457    ///         Ok(acc + v)
1458    ///     } else {
1459    ///         Err("fail")
1460    ///     }
1461    /// })
1462    /// .await;
1463    ///
1464    /// assert_eq!(sum, Err("fail"));
1465    /// # })
1466    /// ```
1467    fn try_fold<T, E, F, B>(&mut self, init: B, f: F) -> TryFoldFuture<'_, Self, F, B>
1468    where
1469        Self: Stream<Item = Result<T, E>> + Unpin + Sized,
1470        F: FnMut(B, T) -> Result<B, E>,
1471    {
1472        TryFoldFuture {
1473            stream: self,
1474            f,
1475            acc: Some(init),
1476        }
1477    }
1478
1479    /// Maps items of the stream to new values using a state value and a closure.
1480    ///
1481    /// Scanning begins with the initial state set to `initial_state`, and then applies `f` to the
1482    /// state and each item in the stream. The stream stops when `f` returns `None`.
1483    ///
1484    /// # Examples
1485    ///
1486    /// ```
1487    /// use futures_lite::stream::{self, StreamExt};
1488    ///
1489    /// # spin_on::spin_on(async {
1490    /// let s = stream::iter(vec![1, 2, 3]);
1491    /// let mut s = s.scan(1, |state, x| {
1492    ///     *state = *state * x;
1493    ///     Some(-*state)
1494    /// });
1495    ///
1496    /// assert_eq!(s.next().await, Some(-1));
1497    /// assert_eq!(s.next().await, Some(-2));
1498    /// assert_eq!(s.next().await, Some(-6));
1499    /// assert_eq!(s.next().await, None);
1500    /// # })
1501    /// ```
1502    fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1503    where
1504        Self: Sized,
1505        F: FnMut(&mut St, Self::Item) -> Option<B>,
1506    {
1507        Scan {
1508            stream: self,
1509            state_f: (initial_state, f),
1510        }
1511    }
1512
1513    /// Fuses the stream so that it stops yielding items after the first [`None`].
1514    ///
1515    /// # Examples
1516    ///
1517    /// ```
1518    /// use futures_lite::stream::{self, StreamExt};
1519    ///
1520    /// # spin_on::spin_on(async {
1521    /// let mut s = stream::once(1).fuse();
1522    ///
1523    /// assert_eq!(s.next().await, Some(1));
1524    /// assert_eq!(s.next().await, None);
1525    /// assert_eq!(s.next().await, None);
1526    /// # })
1527    /// ```
1528    fn fuse(self) -> Fuse<Self>
1529    where
1530        Self: Sized,
1531    {
1532        Fuse {
1533            stream: self,
1534            done: false,
1535        }
1536    }
1537
1538    /// Repeats the stream from beginning to end, forever.
1539    ///
1540    /// # Examples
1541    ///
1542    /// ```
1543    /// use futures_lite::stream::{self, StreamExt};
1544    ///
1545    /// # spin_on::spin_on(async {
1546    /// let mut s = stream::iter(vec![1, 2]).cycle();
1547    ///
1548    /// assert_eq!(s.next().await, Some(1));
1549    /// assert_eq!(s.next().await, Some(2));
1550    /// assert_eq!(s.next().await, Some(1));
1551    /// assert_eq!(s.next().await, Some(2));
1552    /// # });
1553    /// ```
1554    fn cycle(self) -> Cycle<Self>
1555    where
1556        Self: Clone + Sized,
1557    {
1558        Cycle {
1559            orig: self.clone(),
1560            stream: self,
1561        }
1562    }
1563
1564    /// Enumerates items, mapping them to `(index, item)`.
1565    ///
1566    /// # Examples
1567    ///
1568    /// ```
1569    /// use futures_lite::stream::{self, StreamExt};
1570    ///
1571    /// # spin_on::spin_on(async {
1572    /// let s = stream::iter(vec!['a', 'b', 'c']);
1573    /// let mut s = s.enumerate();
1574    ///
1575    /// assert_eq!(s.next().await, Some((0, 'a')));
1576    /// assert_eq!(s.next().await, Some((1, 'b')));
1577    /// assert_eq!(s.next().await, Some((2, 'c')));
1578    /// assert_eq!(s.next().await, None);
1579    /// # });
1580    /// ```
1581    fn enumerate(self) -> Enumerate<Self>
1582    where
1583        Self: Sized,
1584    {
1585        Enumerate { stream: self, i: 0 }
1586    }
1587
1588    /// Creates a stream which can use the [`peek`](Peekable::peek)
1589    /// and [`peek_mut`](Peekable::peek_mut) methods to look at the next
1590    /// element without consuming it.
1591    ///
1592    /// # Examples
1593    ///
1594    /// ```
1595    /// use futures_lite::stream::{self, StreamExt};
1596    ///
1597    /// # spin_on::spin_on(async {
1598    /// let mut stream = stream::iter(1..4).peekable();
1599    /// assert_eq!(stream.peek().await, Some(&1));
1600    /// assert_eq!(stream.next().await, Some(1));
1601    /// assert_eq!(stream.next().await, Some(2));
1602    ///
1603    /// // we can peek multiple times, the stream won't advance
1604    /// assert_eq!(stream.peek().await, Some(&3));
1605    /// assert_eq!(stream.peek().await, Some(&3));
1606    /// assert_eq!(stream.next().await, Some(3));
1607    ///
1608    /// // after the stream is finished, so is peek
1609    /// assert_eq!(stream.peek().await, None);
1610    /// assert_eq!(stream.next().await, None);
1611    /// # });
1612    /// ```
1613    fn peekable(self) -> Peekable<Self>
1614    where
1615        Self: Sized,
1616    {
1617        Peekable {
1618            stream: self,
1619            peeked: None,
1620        }
1621    }
1622
1623    /// Calls a closure on each item and passes it on.
1624    ///
1625    /// # Examples
1626    ///
1627    /// ```
1628    /// use futures_lite::stream::{self, StreamExt};
1629    ///
1630    /// # spin_on::spin_on(async {
1631    /// let s = stream::iter(vec![1, 2, 3, 4, 5]);
1632    ///
1633    /// let sum = s
1634    ///    .inspect(|x| println!("about to filter {}", x))
1635    ///    .filter(|x| x % 2 == 0)
1636    ///    .inspect(|x| println!("made it through filter: {}", x))
1637    ///    .fold(0, |sum, i| sum + i)
1638    ///    .await;
1639    /// # });
1640    /// ```
1641    fn inspect<F>(self, f: F) -> Inspect<Self, F>
1642    where
1643        Self: Sized,
1644        F: FnMut(&Self::Item),
1645    {
1646        Inspect { stream: self, f }
1647    }
1648
1649    /// Gets the `n`th item of the stream.
1650    ///
1651    /// In the end, `n+1` items of the stream will be consumed.
1652    ///
1653    /// # Examples
1654    ///
1655    /// ```
1656    /// use futures_lite::stream::{self, StreamExt};
1657    ///
1658    /// # spin_on::spin_on(async {
1659    /// let mut s = stream::iter(vec![0, 1, 2, 3, 4, 5, 6, 7]);
1660    ///
1661    /// assert_eq!(s.nth(2).await, Some(2));
1662    /// assert_eq!(s.nth(2).await, Some(5));
1663    /// assert_eq!(s.nth(2).await, None);
1664    /// # });
1665    /// ```
1666    fn nth(&mut self, n: usize) -> NthFuture<'_, Self>
1667    where
1668        Self: Unpin,
1669    {
1670        NthFuture { stream: self, n }
1671    }
1672
1673    /// Returns the last item in the stream.
1674    ///
1675    /// # Examples
1676    ///
1677    /// ```
1678    /// use futures_lite::stream::{self, StreamExt};
1679    ///
1680    /// # spin_on::spin_on(async {
1681    /// let s = stream::iter(vec![1, 2, 3, 4]);
1682    /// assert_eq!(s.last().await, Some(4));
1683    ///
1684    /// let s = stream::empty::<i32>();
1685    /// assert_eq!(s.last().await, None);
1686    /// # });
1687    /// ```
1688    fn last(self) -> LastFuture<Self>
1689    where
1690        Self: Sized,
1691    {
1692        LastFuture {
1693            stream: self,
1694            last: None,
1695        }
1696    }
1697
1698    /// Finds the first item of the stream for which `predicate` returns `true`.
1699    ///
1700    /// # Examples
1701    ///
1702    /// ```
1703    /// use futures_lite::stream::{self, StreamExt};
1704    ///
1705    /// # spin_on::spin_on(async {
1706    /// let mut s = stream::iter(vec![11, 12, 13, 14]);
1707    ///
1708    /// assert_eq!(s.find(|x| *x % 2 == 0).await, Some(12));
1709    /// assert_eq!(s.next().await, Some(13));
1710    /// # });
1711    /// ```
1712    fn find<P>(&mut self, predicate: P) -> FindFuture<'_, Self, P>
1713    where
1714        Self: Unpin,
1715        P: FnMut(&Self::Item) -> bool,
1716    {
1717        FindFuture {
1718            stream: self,
1719            predicate,
1720        }
1721    }
1722
1723    /// Applies a closure to items in the stream and returns the first [`Some`] result.
1724    ///
1725    /// # Examples
1726    ///
1727    /// ```
1728    /// use futures_lite::stream::{self, StreamExt};
1729    ///
1730    /// # spin_on::spin_on(async {
1731    /// let mut s = stream::iter(vec!["lol", "NaN", "2", "5"]);
1732    /// let number = s.find_map(|s| s.parse().ok()).await;
1733    ///
1734    /// assert_eq!(number, Some(2));
1735    /// # });
1736    /// ```
1737    fn find_map<F, B>(&mut self, f: F) -> FindMapFuture<'_, Self, F>
1738    where
1739        Self: Unpin,
1740        F: FnMut(Self::Item) -> Option<B>,
1741    {
1742        FindMapFuture { stream: self, f }
1743    }
1744
1745    /// Finds the index of the first item of the stream for which `predicate` returns `true`.
1746    ///
1747    /// # Examples
1748    ///
1749    /// ```
1750    /// use futures_lite::stream::{self, StreamExt};
1751    ///
1752    /// # spin_on::spin_on(async {
1753    /// let mut s = stream::iter(vec![0, 1, 2, 3, 4, 5]);
1754    ///
1755    /// assert_eq!(s.position(|x| x == 2).await, Some(2));
1756    /// assert_eq!(s.position(|x| x == 3).await, Some(0));
1757    /// assert_eq!(s.position(|x| x == 9).await, None);
1758    /// # });
1759    /// ```
1760    fn position<P>(&mut self, predicate: P) -> PositionFuture<'_, Self, P>
1761    where
1762        Self: Unpin,
1763        P: FnMut(Self::Item) -> bool,
1764    {
1765        PositionFuture {
1766            stream: self,
1767            predicate,
1768            index: 0,
1769        }
1770    }
1771
1772    /// Tests if `predicate` returns `true` for all items in the stream.
1773    ///
1774    /// The result is `true` for an empty stream.
1775    ///
1776    /// # Examples
1777    ///
1778    /// ```
1779    /// use futures_lite::stream::{self, StreamExt};
1780    ///
1781    /// # spin_on::spin_on(async {
1782    /// let mut s = stream::iter(vec![1, 2, 3]);
1783    /// assert!(!s.all(|x| x % 2 == 0).await);
1784    ///
1785    /// let mut s = stream::iter(vec![2, 4, 6, 8]);
1786    /// assert!(s.all(|x| x % 2 == 0).await);
1787    ///
1788    /// let mut s = stream::empty::<i32>();
1789    /// assert!(s.all(|x| x % 2 == 0).await);
1790    /// # });
1791    /// ```
1792    fn all<P>(&mut self, predicate: P) -> AllFuture<'_, Self, P>
1793    where
1794        Self: Unpin,
1795        P: FnMut(Self::Item) -> bool,
1796    {
1797        AllFuture {
1798            stream: self,
1799            predicate,
1800        }
1801    }
1802
1803    /// Tests if `predicate` returns `true` for any item in the stream.
1804    ///
1805    /// The result is `false` for an empty stream.
1806    ///
1807    /// # Examples
1808    ///
1809    /// ```
1810    /// use futures_lite::stream::{self, StreamExt};
1811    ///
1812    /// # spin_on::spin_on(async {
1813    /// let mut s = stream::iter(vec![1, 3, 5, 7]);
1814    /// assert!(!s.any(|x| x % 2 == 0).await);
1815    ///
1816    /// let mut s = stream::iter(vec![1, 2, 3]);
1817    /// assert!(s.any(|x| x % 2 == 0).await);
1818    ///
1819    /// let mut s = stream::empty::<i32>();
1820    /// assert!(!s.any(|x| x % 2 == 0).await);
1821    /// # });
1822    /// ```
1823    fn any<P>(&mut self, predicate: P) -> AnyFuture<'_, Self, P>
1824    where
1825        Self: Unpin,
1826        P: FnMut(Self::Item) -> bool,
1827    {
1828        AnyFuture {
1829            stream: self,
1830            predicate,
1831        }
1832    }
1833
1834    /// Calls a closure on each item of the stream.
1835    ///
1836    /// # Examples
1837    ///
1838    /// ```
1839    /// use futures_lite::stream::{self, StreamExt};
1840    ///
1841    /// # spin_on::spin_on(async {
1842    /// let mut s = stream::iter(vec![1, 2, 3]);
1843    /// s.for_each(|s| println!("{}", s)).await;
1844    /// # });
1845    /// ```
1846    fn for_each<F>(self, f: F) -> ForEachFuture<Self, F>
1847    where
1848        Self: Sized,
1849        F: FnMut(Self::Item),
1850    {
1851        ForEachFuture { stream: self, f }
1852    }
1853
1854    /// Calls a fallible closure on each item of the stream, stopping on first error.
1855    ///
1856    /// # Examples
1857    ///
1858    /// ```
1859    /// use futures_lite::stream::{self, StreamExt};
1860    ///
1861    /// # spin_on::spin_on(async {
1862    /// let mut s = stream::iter(vec![0, 1, 2, 3]);
1863    ///
1864    /// let mut v = vec![];
1865    /// let res = s
1866    ///     .try_for_each(|n| {
1867    ///         if n < 2 {
1868    ///             v.push(n);
1869    ///             Ok(())
1870    ///         } else {
1871    ///             Err("too big")
1872    ///         }
1873    ///     })
1874    ///     .await;
1875    ///
1876    /// assert_eq!(v, &[0, 1]);
1877    /// assert_eq!(res, Err("too big"));
1878    /// # });
1879    /// ```
1880    fn try_for_each<F, E>(&mut self, f: F) -> TryForEachFuture<'_, Self, F>
1881    where
1882        Self: Unpin,
1883        F: FnMut(Self::Item) -> Result<(), E>,
1884    {
1885        TryForEachFuture { stream: self, f }
1886    }
1887
1888    /// Zips up two streams into a single stream of pairs.
1889    ///
1890    /// The stream of pairs stops when either of the original two streams is exhausted.
1891    ///
1892    /// # Examples
1893    ///
1894    /// ```
1895    /// use futures_lite::stream::{self, StreamExt};
1896    ///
1897    /// # spin_on::spin_on(async {
1898    /// let l = stream::iter(vec![1, 2, 3]);
1899    /// let r = stream::iter(vec![4, 5, 6, 7]);
1900    /// let mut s = l.zip(r);
1901    ///
1902    /// assert_eq!(s.next().await, Some((1, 4)));
1903    /// assert_eq!(s.next().await, Some((2, 5)));
1904    /// assert_eq!(s.next().await, Some((3, 6)));
1905    /// assert_eq!(s.next().await, None);
1906    /// # });
1907    /// ```
1908    fn zip<U>(self, other: U) -> Zip<Self, U>
1909    where
1910        Self: Sized,
1911        U: Stream,
1912    {
1913        Zip {
1914            item_slot: None,
1915            first: self,
1916            second: other,
1917        }
1918    }
1919
1920    /// Collects a stream of pairs into a pair of collections.
1921    ///
1922    /// # Examples
1923    ///
1924    /// ```
1925    /// use futures_lite::stream::{self, StreamExt};
1926    ///
1927    /// # spin_on::spin_on(async {
1928    /// let s = stream::iter(vec![(1, 2), (3, 4)]);
1929    /// let (left, right): (Vec<_>, Vec<_>) = s.unzip().await;
1930    ///
1931    /// assert_eq!(left, [1, 3]);
1932    /// assert_eq!(right, [2, 4]);
1933    /// # });
1934    /// ```
1935    fn unzip<A, B, FromA, FromB>(self) -> UnzipFuture<Self, FromA, FromB>
1936    where
1937        FromA: Default + Extend<A>,
1938        FromB: Default + Extend<B>,
1939        Self: Stream<Item = (A, B)> + Sized,
1940    {
1941        UnzipFuture {
1942            stream: self,
1943            res: Some(Default::default()),
1944        }
1945    }
1946
1947    /// Merges with `other` stream, preferring items from `self` whenever both streams are ready.
1948    ///
1949    /// # Examples
1950    ///
1951    /// ```
1952    /// use futures_lite::stream::{self, StreamExt};
1953    /// use futures_lite::stream::{once, pending};
1954    ///
1955    /// # spin_on::spin_on(async {
1956    /// assert_eq!(once(1).or(pending()).next().await, Some(1));
1957    /// assert_eq!(pending().or(once(2)).next().await, Some(2));
1958    ///
1959    /// // The first future wins.
1960    /// assert_eq!(once(1).or(once(2)).next().await, Some(1));
1961    /// # })
1962    /// ```
1963    fn or<S>(self, other: S) -> Or<Self, S>
1964    where
1965        Self: Sized,
1966        S: Stream<Item = Self::Item>,
1967    {
1968        Or {
1969            stream1: self,
1970            stream2: other,
1971        }
1972    }
1973
1974    /// Merges with `other` stream, with no preference for either stream when both are ready.
1975    ///
1976    /// # Examples
1977    ///
1978    /// ```
1979    /// use futures_lite::stream::{self, StreamExt};
1980    /// use futures_lite::stream::{empty, once, pending};
1981    ///
1982    /// # spin_on::spin_on(async {
1983    /// assert_eq!(once(1).race(pending()).next().await, Some(1));
1984    /// assert_eq!(pending().race(once(2)).next().await, Some(2));
1985    ///
1986    /// // One of the two stream is randomly chosen as the winner.
1987    /// let res = once(1).race(once(2)).next().await;
1988    ///
1989    /// // If either stream is exhausted, the result of polling the other one is used:
1990    /// assert_eq!(once(1).race(empty()).next().await, Some(1));
1991    /// assert_eq!(empty().race(once(2)).next().await, Some(2));
1992    ///
1993    /// // If both underlying streams are exhausted, so is the combined stream:
1994    /// assert_eq!(empty::<()>().race(empty()).next().await, None);
1995    ///
1996    /// # })
1997    /// ```
1998    #[cfg(all(feature = "std", feature = "race"))]
1999    fn race<S>(self, other: S) -> Race<Self, S>
2000    where
2001        Self: Sized,
2002        S: Stream<Item = Self::Item>,
2003    {
2004        Race {
2005            stream1: self.fuse(),
2006            stream2: other.fuse(),
2007            rng: Rng::new(),
2008        }
2009    }
2010
2011    /// Yields all immediately available values from a stream.
2012    ///
2013    /// This is intended to be used as a way of polling a stream without waiting, similar to the
2014    /// [`try_iter`] function on [`std::sync::mpsc::Receiver`]. For instance, running this stream
2015    /// on an [`async_channel::Receiver`] will return all messages that are currently in the
2016    /// channel, but will not wait for new messages.
2017    ///
2018    /// This returns a [`Stream`] instead of an [`Iterator`] because it still needs access to the
2019    /// polling context in order to poll the underlying stream. Since this stream will never return
2020    /// `Poll::Pending`, wrapping it in [`block_on`] will allow it to be effectively used as an
2021    /// [`Iterator`].
2022    ///
2023    /// This stream is not necessarily fused. After it returns `None`, it can return `Some(x)` in
2024    /// the future if it is polled again.
2025    ///
2026    /// [`try_iter`]: std::sync::mpsc::Receiver::try_iter
2027    /// [`async_channel::Receiver`]: https://docs.rs/async-channel/latest/async_channel/struct.Receiver.html
2028    /// [`Stream`]: crate::stream::Stream
2029    /// [`Iterator`]: std::iter::Iterator
2030    ///
2031    /// # Examples
2032    ///
2033    /// ```
2034    /// use futures_lite::{future, pin};
2035    /// use futures_lite::stream::{self, StreamExt};
2036    ///
2037    /// # #[cfg(feature = "std")] {
2038    /// // A stream that yields two values, returns `Pending`, and then yields one more value.
2039    /// let pend_once = stream::once_future(async {
2040    ///     future::yield_now().await;
2041    ///     3
2042    /// });
2043    /// let s = stream::iter(vec![1, 2]).chain(pend_once);
2044    /// pin!(s);
2045    ///
2046    /// // This will return the first two values, and then `None` because the stream returns
2047    /// // `Pending` after that.
2048    /// let mut iter = stream::block_on(s.drain());
2049    /// assert_eq!(iter.next(), Some(1));
2050    /// assert_eq!(iter.next(), Some(2));
2051    /// assert_eq!(iter.next(), None);
2052    ///
2053    /// // This will return the last value, because the stream returns `Ready` when polled.
2054    /// assert_eq!(iter.next(), Some(3));
2055    /// assert_eq!(iter.next(), None);
2056    /// # }
2057    /// ```
2058    fn drain(&mut self) -> Drain<'_, Self> {
2059        Drain { stream: self }
2060    }
2061
2062    /// Boxes the stream and changes its type to `dyn Stream + Send + 'a`.
2063    ///
2064    /// # Examples
2065    ///
2066    /// ```
2067    /// use futures_lite::stream::{self, StreamExt};
2068    ///
2069    /// # spin_on::spin_on(async {
2070    /// let a = stream::once(1);
2071    /// let b = stream::empty();
2072    ///
2073    /// // Streams of different types can be stored in
2074    /// // the same collection when they are boxed:
2075    /// let streams = vec![a.boxed(), b.boxed()];
2076    /// # })
2077    /// ```
2078    #[cfg(feature = "alloc")]
2079    fn boxed<'a>(self) -> Pin<Box<dyn Stream<Item = Self::Item> + Send + 'a>>
2080    where
2081        Self: Send + Sized + 'a,
2082    {
2083        Box::pin(self)
2084    }
2085
2086    /// Boxes the stream and changes its type to `dyn Stream + 'a`.
2087    ///
2088    /// # Examples
2089    ///
2090    /// ```
2091    /// use futures_lite::stream::{self, StreamExt};
2092    ///
2093    /// # spin_on::spin_on(async {
2094    /// let a = stream::once(1);
2095    /// let b = stream::empty();
2096    ///
2097    /// // Streams of different types can be stored in
2098    /// // the same collection when they are boxed:
2099    /// let streams = vec![a.boxed_local(), b.boxed_local()];
2100    /// # })
2101    /// ```
2102    #[cfg(feature = "alloc")]
2103    fn boxed_local<'a>(self) -> Pin<Box<dyn Stream<Item = Self::Item> + 'a>>
2104    where
2105        Self: Sized + 'a,
2106    {
2107        Box::pin(self)
2108    }
2109}
2110
2111impl<S: Stream + ?Sized> StreamExt for S {}
2112
2113/// Type alias for `Pin<Box<dyn Stream<Item = T> + Send + 'static>>`.
2114///
2115/// # Examples
2116///
2117/// ```
2118/// use futures_lite::stream::{self, StreamExt};
2119///
2120/// // These two lines are equivalent:
2121/// let s1: stream::Boxed<i32> = stream::once(7).boxed();
2122/// let s2: stream::Boxed<i32> = Box::pin(stream::once(7));
2123/// ```
2124#[cfg(feature = "alloc")]
2125pub type Boxed<T> = Pin<Box<dyn Stream<Item = T> + Send + 'static>>;
2126
2127/// Type alias for `Pin<Box<dyn Stream<Item = T> + 'static>>`.
2128///
2129/// # Examples
2130///
2131/// ```
2132/// use futures_lite::stream::{self, StreamExt};
2133///
2134/// // These two lines are equivalent:
2135/// let s1: stream::BoxedLocal<i32> = stream::once(7).boxed_local();
2136/// let s2: stream::BoxedLocal<i32> = Box::pin(stream::once(7));
2137/// ```
2138#[cfg(feature = "alloc")]
2139pub type BoxedLocal<T> = Pin<Box<dyn Stream<Item = T> + 'static>>;
2140
2141/// Future for the [`StreamExt::next()`] method.
2142#[derive(Debug)]
2143#[must_use = "futures do nothing unless you `.await` or poll them"]
2144pub struct NextFuture<'a, S: ?Sized> {
2145    stream: &'a mut S,
2146}
2147
2148impl<S: Unpin + ?Sized> Unpin for NextFuture<'_, S> {}
2149
2150impl<S: Stream + Unpin + ?Sized> Future for NextFuture<'_, S> {
2151    type Output = Option<S::Item>;
2152
2153    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2154        self.stream.poll_next(cx)
2155    }
2156}
2157
2158/// Future for the [`StreamExt::try_next()`] method.
2159#[derive(Debug)]
2160#[must_use = "futures do nothing unless you `.await` or poll them"]
2161pub struct TryNextFuture<'a, S: ?Sized> {
2162    stream: &'a mut S,
2163}
2164
2165impl<S: Unpin + ?Sized> Unpin for TryNextFuture<'_, S> {}
2166
2167impl<T, E, S> Future for TryNextFuture<'_, S>
2168where
2169    S: Stream<Item = Result<T, E>> + Unpin + ?Sized,
2170{
2171    type Output = Result<Option<T>, E>;
2172
2173    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2174        let res = ready!(self.stream.poll_next(cx));
2175        Poll::Ready(res.transpose())
2176    }
2177}
2178
2179pin_project! {
2180    /// Future for the [`StreamExt::count()`] method.
2181    #[derive(Debug)]
2182    #[must_use = "futures do nothing unless you `.await` or poll them"]
2183    pub struct CountFuture<S: ?Sized> {
2184        count: usize,
2185        #[pin]
2186        stream: S,
2187    }
2188}
2189
2190impl<S: Stream + ?Sized> Future for CountFuture<S> {
2191    type Output = usize;
2192
2193    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2194        loop {
2195            match ready!(self.as_mut().project().stream.poll_next(cx)) {
2196                None => return Poll::Ready(self.count),
2197                Some(_) => *self.as_mut().project().count += 1,
2198            }
2199        }
2200    }
2201}
2202
2203pin_project! {
2204    /// Future for the [`StreamExt::collect()`] method.
2205    #[derive(Debug)]
2206    #[must_use = "futures do nothing unless you `.await` or poll them"]
2207    pub struct CollectFuture<S, C> {
2208        #[pin]
2209        stream: S,
2210        collection: C,
2211    }
2212}
2213
2214impl<S, C> Future for CollectFuture<S, C>
2215where
2216    S: Stream,
2217    C: Default + Extend<S::Item>,
2218{
2219    type Output = C;
2220
2221    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<C> {
2222        let mut this = self.as_mut().project();
2223        loop {
2224            match ready!(this.stream.as_mut().poll_next(cx)) {
2225                Some(e) => this.collection.extend(Some(e)),
2226                None => return Poll::Ready(mem::take(self.project().collection)),
2227            }
2228        }
2229    }
2230}
2231
2232pin_project! {
2233    /// Future for the [`StreamExt::try_collect()`] method.
2234    #[derive(Debug)]
2235    #[must_use = "futures do nothing unless you `.await` or poll them"]
2236    pub struct TryCollectFuture<S, C> {
2237        #[pin]
2238        stream: S,
2239        items: C,
2240    }
2241}
2242
2243impl<T, E, S, C> Future for TryCollectFuture<S, C>
2244where
2245    S: Stream<Item = Result<T, E>>,
2246    C: Default + Extend<T>,
2247{
2248    type Output = Result<C, E>;
2249
2250    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2251        let mut this = self.project();
2252        Poll::Ready(Ok(loop {
2253            match ready!(this.stream.as_mut().poll_next(cx)?) {
2254                Some(x) => this.items.extend(Some(x)),
2255                None => break mem::take(this.items),
2256            }
2257        }))
2258    }
2259}
2260
2261pin_project! {
2262    /// Future for the [`StreamExt::partition()`] method.
2263    #[derive(Debug)]
2264    #[must_use = "futures do nothing unless you `.await` or poll them"]
2265    pub struct PartitionFuture<S, P, B> {
2266        #[pin]
2267        stream: S,
2268        predicate: P,
2269        res: Option<(B, B)>,
2270    }
2271}
2272
2273impl<S, P, B> Future for PartitionFuture<S, P, B>
2274where
2275    S: Stream + Sized,
2276    P: FnMut(&S::Item) -> bool,
2277    B: Default + Extend<S::Item>,
2278{
2279    type Output = (B, B);
2280
2281    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2282        let mut this = self.project();
2283        loop {
2284            match ready!(this.stream.as_mut().poll_next(cx)) {
2285                Some(v) => {
2286                    let res = this.res.as_mut().unwrap();
2287                    if (this.predicate)(&v) {
2288                        res.0.extend(Some(v))
2289                    } else {
2290                        res.1.extend(Some(v))
2291                    }
2292                }
2293                None => return Poll::Ready(this.res.take().unwrap()),
2294            }
2295        }
2296    }
2297}
2298
2299pin_project! {
2300    /// Future for the [`StreamExt::fold()`] method.
2301    #[derive(Debug)]
2302    #[must_use = "futures do nothing unless you `.await` or poll them"]
2303    pub struct FoldFuture<S, F, T> {
2304        #[pin]
2305        stream: S,
2306        f: F,
2307        acc: Option<T>,
2308    }
2309}
2310
2311impl<S, F, T> Future for FoldFuture<S, F, T>
2312where
2313    S: Stream,
2314    F: FnMut(T, S::Item) -> T,
2315{
2316    type Output = T;
2317
2318    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2319        let mut this = self.project();
2320        loop {
2321            match ready!(this.stream.as_mut().poll_next(cx)) {
2322                Some(v) => {
2323                    let old = this.acc.take().unwrap();
2324                    let new = (this.f)(old, v);
2325                    *this.acc = Some(new);
2326                }
2327                None => return Poll::Ready(this.acc.take().unwrap()),
2328            }
2329        }
2330    }
2331}
2332
2333/// Future for the [`StreamExt::try_fold()`] method.
2334#[derive(Debug)]
2335#[must_use = "futures do nothing unless you `.await` or poll them"]
2336pub struct TryFoldFuture<'a, S, F, B> {
2337    stream: &'a mut S,
2338    f: F,
2339    acc: Option<B>,
2340}
2341
2342impl<S, F, B> Unpin for TryFoldFuture<'_, S, F, B> {}
2343
2344impl<T, E, S, F, B> Future for TryFoldFuture<'_, S, F, B>
2345where
2346    S: Stream<Item = Result<T, E>> + Unpin,
2347    F: FnMut(B, T) -> Result<B, E>,
2348{
2349    type Output = Result<B, E>;
2350
2351    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2352        loop {
2353            match ready!(self.stream.poll_next(cx)) {
2354                Some(Err(e)) => return Poll::Ready(Err(e)),
2355                Some(Ok(t)) => {
2356                    let old = self.acc.take().unwrap();
2357                    let new = (&mut self.f)(old, t);
2358
2359                    match new {
2360                        Ok(t) => self.acc = Some(t),
2361                        Err(e) => return Poll::Ready(Err(e)),
2362                    }
2363                }
2364                None => return Poll::Ready(Ok(self.acc.take().unwrap())),
2365            }
2366        }
2367    }
2368}
2369
2370pin_project! {
2371    /// Stream for the [`StreamExt::scan()`] method.
2372    #[derive(Clone, Debug)]
2373    #[must_use = "streams do nothing unless polled"]
2374    pub struct Scan<S, St, F> {
2375        #[pin]
2376        stream: S,
2377        state_f: (St, F),
2378    }
2379}
2380
2381impl<S, St, F, B> Stream for Scan<S, St, F>
2382where
2383    S: Stream,
2384    F: FnMut(&mut St, S::Item) -> Option<B>,
2385{
2386    type Item = B;
2387
2388    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<B>> {
2389        let mut this = self.project();
2390        this.stream.as_mut().poll_next(cx).map(|item| {
2391            item.and_then(|item| {
2392                let (state, f) = this.state_f;
2393                f(state, item)
2394            })
2395        })
2396    }
2397}
2398
2399pin_project! {
2400    /// Stream for the [`StreamExt::fuse()`] method.
2401    #[derive(Clone, Debug)]
2402    #[must_use = "streams do nothing unless polled"]
2403    pub struct Fuse<S> {
2404        #[pin]
2405        stream: S,
2406        done: bool,
2407    }
2408}
2409
2410impl<S: Stream> Stream for Fuse<S> {
2411    type Item = S::Item;
2412
2413    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
2414        let this = self.project();
2415
2416        if *this.done {
2417            Poll::Ready(None)
2418        } else {
2419            let next = ready!(this.stream.poll_next(cx));
2420            if next.is_none() {
2421                *this.done = true;
2422            }
2423            Poll::Ready(next)
2424        }
2425    }
2426}
2427
2428pin_project! {
2429    /// Stream for the [`StreamExt::map()`] method.
2430    #[derive(Clone, Debug)]
2431    #[must_use = "streams do nothing unless polled"]
2432    pub struct Map<S, F> {
2433        #[pin]
2434        stream: S,
2435        f: F,
2436    }
2437}
2438
2439impl<S, F, T> Stream for Map<S, F>
2440where
2441    S: Stream,
2442    F: FnMut(S::Item) -> T,
2443{
2444    type Item = T;
2445
2446    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2447        let this = self.project();
2448        let next = ready!(this.stream.poll_next(cx));
2449        Poll::Ready(next.map(this.f))
2450    }
2451
2452    fn size_hint(&self) -> (usize, Option<usize>) {
2453        self.stream.size_hint()
2454    }
2455}
2456
2457pin_project! {
2458    /// Stream for the [`StreamExt::flat_map()`] method.
2459    #[derive(Clone, Debug)]
2460    #[must_use = "streams do nothing unless polled"]
2461    pub struct FlatMap<S, U, F> {
2462        #[pin]
2463        stream: Map<S, F>,
2464        #[pin]
2465        inner_stream: Option<U>,
2466    }
2467}
2468
2469impl<S, U, F> Stream for FlatMap<S, U, F>
2470where
2471    S: Stream,
2472    U: Stream,
2473    F: FnMut(S::Item) -> U,
2474{
2475    type Item = U::Item;
2476
2477    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2478        let mut this = self.project();
2479        loop {
2480            if let Some(inner) = this.inner_stream.as_mut().as_pin_mut() {
2481                match ready!(inner.poll_next(cx)) {
2482                    Some(item) => return Poll::Ready(Some(item)),
2483                    None => this.inner_stream.set(None),
2484                }
2485            }
2486
2487            match ready!(this.stream.as_mut().poll_next(cx)) {
2488                Some(stream) => this.inner_stream.set(Some(stream)),
2489                None => return Poll::Ready(None),
2490            }
2491        }
2492    }
2493}
2494
2495pin_project! {
2496    /// Stream for the [`StreamExt::flatten()`] method.
2497    #[derive(Clone, Debug)]
2498    #[must_use = "streams do nothing unless polled"]
2499    pub struct Flatten<S: Stream> {
2500        #[pin]
2501        stream: S,
2502        #[pin]
2503        inner_stream: Option<S::Item>,
2504    }
2505}
2506
2507impl<S, U> Stream for Flatten<S>
2508where
2509    S: Stream<Item = U>,
2510    U: Stream,
2511{
2512    type Item = U::Item;
2513
2514    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2515        let mut this = self.project();
2516        loop {
2517            if let Some(inner) = this.inner_stream.as_mut().as_pin_mut() {
2518                match ready!(inner.poll_next(cx)) {
2519                    Some(item) => return Poll::Ready(Some(item)),
2520                    None => this.inner_stream.set(None),
2521                }
2522            }
2523
2524            match ready!(this.stream.as_mut().poll_next(cx)) {
2525                Some(inner) => this.inner_stream.set(Some(inner)),
2526                None => return Poll::Ready(None),
2527            }
2528        }
2529    }
2530}
2531
2532pin_project! {
2533    /// Stream for the [`StreamExt::then()`] method.
2534    #[derive(Clone, Debug)]
2535    #[must_use = "streams do nothing unless polled"]
2536    pub struct Then<S, F, Fut> {
2537        #[pin]
2538        stream: S,
2539        #[pin]
2540        future: Option<Fut>,
2541        f: F,
2542    }
2543}
2544
2545impl<S, F, Fut> Stream for Then<S, F, Fut>
2546where
2547    S: Stream,
2548    F: FnMut(S::Item) -> Fut,
2549    Fut: Future,
2550{
2551    type Item = Fut::Output;
2552
2553    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2554        let mut this = self.project();
2555
2556        loop {
2557            if let Some(fut) = this.future.as_mut().as_pin_mut() {
2558                let item = ready!(fut.poll(cx));
2559                this.future.set(None);
2560                return Poll::Ready(Some(item));
2561            } else if let Some(item) = ready!(this.stream.as_mut().poll_next(cx)) {
2562                this.future.set(Some((this.f)(item)));
2563            } else {
2564                return Poll::Ready(None);
2565            }
2566        }
2567    }
2568
2569    fn size_hint(&self) -> (usize, Option<usize>) {
2570        let future_len = self.future.is_some() as usize;
2571        let (lower, upper) = self.stream.size_hint();
2572        let lower = lower.saturating_add(future_len);
2573        let upper = upper.and_then(|u| u.checked_add(future_len));
2574        (lower, upper)
2575    }
2576}
2577
2578pin_project! {
2579    /// Stream for the [`StreamExt::filter()`] method.
2580    #[derive(Clone, Debug)]
2581    #[must_use = "streams do nothing unless polled"]
2582    pub struct Filter<S, P> {
2583        #[pin]
2584        stream: S,
2585        predicate: P,
2586    }
2587}
2588
2589impl<S, P> Stream for Filter<S, P>
2590where
2591    S: Stream,
2592    P: FnMut(&S::Item) -> bool,
2593{
2594    type Item = S::Item;
2595
2596    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2597        let mut this = self.project();
2598        loop {
2599            match ready!(this.stream.as_mut().poll_next(cx)) {
2600                None => return Poll::Ready(None),
2601                Some(v) if (this.predicate)(&v) => return Poll::Ready(Some(v)),
2602                Some(_) => {}
2603            }
2604        }
2605    }
2606
2607    fn size_hint(&self) -> (usize, Option<usize>) {
2608        let (_, hi) = self.stream.size_hint();
2609
2610        // If the filter matches all of the elements, it will match the stream's upper bound.
2611        // If the filter matches none of the elements, there will be zero returned values.
2612        (0, hi)
2613    }
2614}
2615
2616/// Merges two streams, preferring items from `stream1` whenever both streams are ready.
2617///
2618/// # Examples
2619///
2620/// ```
2621/// use futures_lite::stream::{self, once, pending, StreamExt};
2622///
2623/// # spin_on::spin_on(async {
2624/// assert_eq!(stream::or(once(1), pending()).next().await, Some(1));
2625/// assert_eq!(stream::or(pending(), once(2)).next().await, Some(2));
2626///
2627/// // The first stream wins.
2628/// assert_eq!(stream::or(once(1), once(2)).next().await, Some(1));
2629/// # })
2630/// ```
2631pub fn or<T, S1, S2>(stream1: S1, stream2: S2) -> Or<S1, S2>
2632where
2633    S1: Stream<Item = T>,
2634    S2: Stream<Item = T>,
2635{
2636    Or { stream1, stream2 }
2637}
2638
2639pin_project! {
2640    /// Stream for the [`or()`] function and the [`StreamExt::or()`] method.
2641    #[derive(Clone, Debug)]
2642    #[must_use = "streams do nothing unless polled"]
2643    pub struct Or<S1, S2> {
2644        #[pin]
2645        stream1: S1,
2646        #[pin]
2647        stream2: S2,
2648    }
2649}
2650
2651impl<T, S1, S2> Stream for Or<S1, S2>
2652where
2653    S1: Stream<Item = T>,
2654    S2: Stream<Item = T>,
2655{
2656    type Item = T;
2657
2658    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2659        let mut this = self.project();
2660
2661        if let Poll::Ready(Some(t)) = this.stream1.as_mut().poll_next(cx) {
2662            return Poll::Ready(Some(t));
2663        }
2664        this.stream2.as_mut().poll_next(cx)
2665    }
2666}
2667
2668/// Merges two streams, with no preference for either stream when both are ready.
2669///
2670/// # Examples
2671///
2672/// ```
2673/// use futures_lite::stream::{self, empty, once, pending, StreamExt};
2674///
2675/// # spin_on::spin_on(async {
2676/// assert_eq!(stream::race(once(1), pending()).next().await, Some(1));
2677/// assert_eq!(stream::race(pending(), once(2)).next().await, Some(2));
2678///
2679/// // One of the two stream is randomly chosen as the winner.
2680/// let res = stream::race(once(1), once(2)).next().await;
2681///
2682/// // If either stream is exhausted, the result of polling the other one is used:
2683/// assert_eq!(once(1).race(empty()).next().await, Some(1));
2684/// assert_eq!(empty().race(once(2)).next().await, Some(2));
2685///
2686/// // If both underlying streams are exhausted, so is the combined stream:
2687/// assert_eq!(empty::<()>().race(empty()).next().await, None);
2688/// # })
2689/// ```
2690#[cfg(all(feature = "std", feature = "race"))]
2691pub fn race<T, S1, S2>(stream1: S1, stream2: S2) -> Race<S1, S2>
2692where
2693    S1: Stream<Item = T>,
2694    S2: Stream<Item = T>,
2695{
2696    Race {
2697        stream1: stream1.fuse(),
2698        stream2: stream2.fuse(),
2699        rng: Rng::new(),
2700    }
2701}
2702
2703/// Races two streams, but with a user-provided seed for randomness.
2704///
2705/// # Examples
2706///
2707/// ```
2708/// use futures_lite::stream::{self, once, pending, StreamExt};
2709///
2710/// // A fixed seed is used for reproducibility.
2711/// const SEED: u64 = 123;
2712///
2713/// # spin_on::spin_on(async {
2714/// assert_eq!(stream::race_with_seed(once(1), pending(), SEED).next().await, Some(1));
2715/// assert_eq!(stream::race_with_seed(pending(), once(2), SEED).next().await, Some(2));
2716///
2717/// // One of the two stream is randomly chosen as the winner.
2718/// let res = stream::race_with_seed(once(1), once(2), SEED).next().await;
2719/// # })
2720/// ```
2721#[cfg(feature = "race")]
2722pub fn race_with_seed<T, S1, S2>(stream1: S1, stream2: S2, seed: u64) -> Race<S1, S2>
2723where
2724    S1: Stream<Item = T>,
2725    S2: Stream<Item = T>,
2726{
2727    Race {
2728        stream1: stream1.fuse(),
2729        stream2: stream2.fuse(),
2730        rng: Rng::with_seed(seed),
2731    }
2732}
2733
2734#[cfg(feature = "race")]
2735pin_project! {
2736    /// Stream for the [`race()`] function and the [`StreamExt::race()`] method.
2737    #[derive(Clone, Debug)]
2738    #[must_use = "streams do nothing unless polled"]
2739    pub struct Race<S1, S2> {
2740        #[pin]
2741        stream1: Fuse<S1>,
2742        #[pin]
2743        stream2: Fuse<S2>,
2744        rng: Rng,
2745    }
2746}
2747
2748#[cfg(feature = "race")]
2749impl<T, S1, S2> Stream for Race<S1, S2>
2750where
2751    S1: Stream<Item = T>,
2752    S2: Stream<Item = T>,
2753{
2754    type Item = T;
2755
2756    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2757        let mut this = self.project();
2758
2759        if this.rng.bool() {
2760            if !this.stream1.done {
2761                if let Poll::Ready(Some(t)) = this.stream1.as_mut().poll_next(cx) {
2762                    return Poll::Ready(Some(t));
2763                }
2764            }
2765            this.stream2.as_mut().poll_next(cx)
2766        } else {
2767            if !this.stream2.done {
2768                if let Poll::Ready(Some(t)) = this.stream2.as_mut().poll_next(cx) {
2769                    return Poll::Ready(Some(t));
2770                }
2771            }
2772            this.stream1.as_mut().poll_next(cx)
2773        }
2774    }
2775}
2776
2777pin_project! {
2778    /// Stream for the [`StreamExt::filter_map()`] method.
2779    #[derive(Clone, Debug)]
2780    #[must_use = "streams do nothing unless polled"]
2781    pub struct FilterMap<S, F> {
2782        #[pin]
2783        stream: S,
2784        f: F,
2785    }
2786}
2787
2788impl<S, F, T> Stream for FilterMap<S, F>
2789where
2790    S: Stream,
2791    F: FnMut(S::Item) -> Option<T>,
2792{
2793    type Item = T;
2794
2795    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2796        let mut this = self.project();
2797        loop {
2798            match ready!(this.stream.as_mut().poll_next(cx)) {
2799                None => return Poll::Ready(None),
2800                Some(v) => {
2801                    if let Some(t) = (this.f)(v) {
2802                        return Poll::Ready(Some(t));
2803                    }
2804                }
2805            }
2806        }
2807    }
2808}
2809
2810pin_project! {
2811    /// Stream for the [`StreamExt::take()`] method.
2812    #[derive(Clone, Debug)]
2813    #[must_use = "streams do nothing unless polled"]
2814    pub struct Take<S> {
2815        #[pin]
2816        stream: S,
2817        n: usize,
2818    }
2819}
2820
2821impl<S: Stream> Stream for Take<S> {
2822    type Item = S::Item;
2823
2824    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
2825        let this = self.project();
2826
2827        if *this.n == 0 {
2828            Poll::Ready(None)
2829        } else {
2830            let next = ready!(this.stream.poll_next(cx));
2831            match next {
2832                Some(_) => *this.n -= 1,
2833                None => *this.n = 0,
2834            }
2835            Poll::Ready(next)
2836        }
2837    }
2838}
2839
2840pin_project! {
2841    /// Stream for the [`StreamExt::take_while()`] method.
2842    #[derive(Clone, Debug)]
2843    #[must_use = "streams do nothing unless polled"]
2844    pub struct TakeWhile<S, P> {
2845        #[pin]
2846        stream: S,
2847        predicate: P,
2848    }
2849}
2850
2851impl<S, P> Stream for TakeWhile<S, P>
2852where
2853    S: Stream,
2854    P: FnMut(&S::Item) -> bool,
2855{
2856    type Item = S::Item;
2857
2858    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2859        let this = self.project();
2860
2861        match ready!(this.stream.poll_next(cx)) {
2862            Some(v) => {
2863                if (this.predicate)(&v) {
2864                    Poll::Ready(Some(v))
2865                } else {
2866                    Poll::Ready(None)
2867                }
2868            }
2869            None => Poll::Ready(None),
2870        }
2871    }
2872}
2873
2874pin_project! {
2875    /// Stream for the [`StreamExt::map_while()`] method.
2876    #[derive(Clone, Debug)]
2877    #[must_use = "streams do nothing unless polled"]
2878    pub struct MapWhile<S, P> {
2879        #[pin]
2880        stream: S,
2881        predicate: P,
2882    }
2883}
2884
2885impl<B, S, P> Stream for MapWhile<S, P>
2886where
2887    S: Stream,
2888    P: FnMut(S::Item) -> Option<B>,
2889{
2890    type Item = B;
2891
2892    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2893        let this = self.project();
2894
2895        match ready!(this.stream.poll_next(cx)) {
2896            Some(v) => Poll::Ready((this.predicate)(v)),
2897            None => Poll::Ready(None),
2898        }
2899    }
2900}
2901
2902pin_project! {
2903    /// Stream for the [`StreamExt::skip()`] method.
2904    #[derive(Clone, Debug)]
2905    #[must_use = "streams do nothing unless polled"]
2906    pub struct Skip<S> {
2907        #[pin]
2908        stream: S,
2909        n: usize,
2910    }
2911}
2912
2913impl<S: Stream> Stream for Skip<S> {
2914    type Item = S::Item;
2915
2916    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2917        let mut this = self.project();
2918        loop {
2919            match ready!(this.stream.as_mut().poll_next(cx)) {
2920                Some(v) => match *this.n {
2921                    0 => return Poll::Ready(Some(v)),
2922                    _ => *this.n -= 1,
2923                },
2924                None => return Poll::Ready(None),
2925            }
2926        }
2927    }
2928}
2929
2930pin_project! {
2931    /// Stream for the [`StreamExt::skip_while()`] method.
2932    #[derive(Clone, Debug)]
2933    #[must_use = "streams do nothing unless polled"]
2934    pub struct SkipWhile<S, P> {
2935        #[pin]
2936        stream: S,
2937        predicate: Option<P>,
2938    }
2939}
2940
2941impl<S, P> Stream for SkipWhile<S, P>
2942where
2943    S: Stream,
2944    P: FnMut(&S::Item) -> bool,
2945{
2946    type Item = S::Item;
2947
2948    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2949        let mut this = self.project();
2950        loop {
2951            match ready!(this.stream.as_mut().poll_next(cx)) {
2952                Some(v) => match this.predicate {
2953                    Some(p) => {
2954                        if !p(&v) {
2955                            *this.predicate = None;
2956                            return Poll::Ready(Some(v));
2957                        }
2958                    }
2959                    None => return Poll::Ready(Some(v)),
2960                },
2961                None => return Poll::Ready(None),
2962            }
2963        }
2964    }
2965}
2966
2967pin_project! {
2968    /// Stream for the [`StreamExt::step_by()`] method.
2969    #[derive(Clone, Debug)]
2970    #[must_use = "streams do nothing unless polled"]
2971    pub struct StepBy<S> {
2972        #[pin]
2973        stream: S,
2974        step: usize,
2975        i: usize,
2976    }
2977}
2978
2979impl<S: Stream> Stream for StepBy<S> {
2980    type Item = S::Item;
2981
2982    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2983        let mut this = self.project();
2984        loop {
2985            match ready!(this.stream.as_mut().poll_next(cx)) {
2986                Some(v) => {
2987                    if *this.i == 0 {
2988                        *this.i = *this.step - 1;
2989                        return Poll::Ready(Some(v));
2990                    } else {
2991                        *this.i -= 1;
2992                    }
2993                }
2994                None => return Poll::Ready(None),
2995            }
2996        }
2997    }
2998}
2999
3000pin_project! {
3001    /// Stream for the [`StreamExt::chain()`] method.
3002    #[derive(Clone, Debug)]
3003    #[must_use = "streams do nothing unless polled"]
3004    pub struct Chain<S, U> {
3005        #[pin]
3006        first: Fuse<S>,
3007        #[pin]
3008        second: Fuse<U>,
3009    }
3010}
3011
3012impl<S: Stream, U: Stream<Item = S::Item>> Stream for Chain<S, U> {
3013    type Item = S::Item;
3014
3015    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3016        let mut this = self.project();
3017
3018        if !this.first.done {
3019            let next = ready!(this.first.as_mut().poll_next(cx));
3020            if let Some(next) = next {
3021                return Poll::Ready(Some(next));
3022            }
3023        }
3024
3025        if !this.second.done {
3026            let next = ready!(this.second.as_mut().poll_next(cx));
3027            if let Some(next) = next {
3028                return Poll::Ready(Some(next));
3029            }
3030        }
3031
3032        if this.first.done && this.second.done {
3033            Poll::Ready(None)
3034        } else {
3035            Poll::Pending
3036        }
3037    }
3038}
3039
3040pin_project! {
3041    /// Stream for the [`StreamExt::cloned()`] method.
3042    #[derive(Clone, Debug)]
3043    #[must_use = "streams do nothing unless polled"]
3044    pub struct Cloned<S> {
3045        #[pin]
3046        stream: S,
3047    }
3048}
3049
3050impl<'a, S, T: 'a> Stream for Cloned<S>
3051where
3052    S: Stream<Item = &'a T>,
3053    T: Clone,
3054{
3055    type Item = T;
3056
3057    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3058        let this = self.project();
3059        let next = ready!(this.stream.poll_next(cx));
3060        Poll::Ready(next.cloned())
3061    }
3062}
3063
3064pin_project! {
3065    /// Stream for the [`StreamExt::copied()`] method.
3066    #[derive(Clone, Debug)]
3067    #[must_use = "streams do nothing unless polled"]
3068    pub struct Copied<S> {
3069        #[pin]
3070        stream: S,
3071    }
3072}
3073
3074impl<'a, S, T: 'a> Stream for Copied<S>
3075where
3076    S: Stream<Item = &'a T>,
3077    T: Copy,
3078{
3079    type Item = T;
3080
3081    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3082        let this = self.project();
3083        let next = ready!(this.stream.poll_next(cx));
3084        Poll::Ready(next.copied())
3085    }
3086}
3087
3088pin_project! {
3089    /// Stream for the [`StreamExt::cycle()`] method.
3090    #[derive(Clone, Debug)]
3091    #[must_use = "streams do nothing unless polled"]
3092    pub struct Cycle<S> {
3093        orig: S,
3094        #[pin]
3095        stream: S,
3096    }
3097}
3098
3099impl<S> Stream for Cycle<S>
3100where
3101    S: Stream + Clone,
3102{
3103    type Item = S::Item;
3104
3105    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3106        match ready!(self.as_mut().project().stream.as_mut().poll_next(cx)) {
3107            Some(item) => Poll::Ready(Some(item)),
3108            None => {
3109                let new = self.as_mut().orig.clone();
3110                self.as_mut().project().stream.set(new);
3111                self.project().stream.poll_next(cx)
3112            }
3113        }
3114    }
3115}
3116
3117pin_project! {
3118    /// Stream for the [`StreamExt::enumerate()`] method.
3119    #[derive(Clone, Debug)]
3120    #[must_use = "streams do nothing unless polled"]
3121    pub struct Enumerate<S> {
3122        #[pin]
3123        stream: S,
3124        i: usize,
3125    }
3126}
3127
3128impl<S> Stream for Enumerate<S>
3129where
3130    S: Stream,
3131{
3132    type Item = (usize, S::Item);
3133
3134    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3135        let this = self.project();
3136
3137        match ready!(this.stream.poll_next(cx)) {
3138            Some(v) => {
3139                let ret = (*this.i, v);
3140                *this.i += 1;
3141                Poll::Ready(Some(ret))
3142            }
3143            None => Poll::Ready(None),
3144        }
3145    }
3146}
3147
3148pin_project! {
3149    /// Stream for the [`StreamExt::peekable()`] method.
3150    #[derive(Clone, Debug)]
3151    #[must_use = "streams do nothing unless polled"]
3152    pub struct Peekable<S: Stream> {
3153        #[pin]
3154        stream: S,
3155        peeked: Option<Option<S::Item>>,
3156    }
3157}
3158
3159impl<S: Stream> Peekable<S> {
3160    /// Returns a reference to the [`next`](StreamExt::next) value without advancing the stream.
3161    ///
3162    /// # Examples
3163    ///
3164    /// ```
3165    /// use futures_lite::stream::{self, StreamExt};
3166    ///
3167    /// # spin_on::spin_on(async {
3168    /// let mut stream = stream::iter(0..3).peekable();
3169    ///
3170    /// // multiple `peek` calls don't advance the stream further
3171    /// assert_eq!(stream.peek().await, Some(&0));
3172    /// assert_eq!(stream.peek().await, Some(&0));
3173    ///
3174    /// // the `next` call advances the stream and consumes the value
3175    /// assert_eq!(stream.next().await, Some(0));
3176    ///
3177    /// assert_eq!(stream.peek().await, Some(&1));
3178    /// assert_eq!(stream.next().await, Some(1));
3179    /// assert_eq!(stream.next().await, Some(2));
3180    ///
3181    /// assert_eq!(stream.peek().await, None);
3182    /// assert_eq!(stream.next().await, None);
3183    /// # });
3184    /// ```
3185    pub fn peek(&mut self) -> Peek<'_, S>
3186    where
3187        Self: Unpin,
3188    {
3189        Peek {
3190            state: Some(Pin::new(self)),
3191        }
3192    }
3193
3194    /// Returns a mutable reference to the [`next`](StreamExt::next) value without advancing the stream.
3195    ///
3196    /// # Examples
3197    ///
3198    /// ```
3199    /// use futures_lite::stream::{self, StreamExt};
3200    ///
3201    /// # spin_on::spin_on(async {
3202    /// let mut stream = stream::iter(0..2).peekable();
3203    /// assert_eq!(stream.peek_mut().await, Some(&mut 0));
3204    /// assert_eq!(stream.next().await, Some(0));
3205    ///
3206    /// // use `peek_mut` to mutate next item
3207    /// if let Some(p) = stream.peek_mut().await {
3208    ///     *p = 10;
3209    /// }
3210    ///
3211    /// assert_eq!(stream.next().await, Some(10));
3212    ///
3213    /// assert_eq!(stream.peek().await, None);
3214    /// assert_eq!(stream.next().await, None);
3215    /// # });
3216    /// ```
3217    pub fn peek_mut(&mut self) -> PeekMut<'_, S>
3218    where
3219        Self: Unpin,
3220    {
3221        PeekMut {
3222            state: Some(Pin::new(self)),
3223        }
3224    }
3225
3226    /// The poll-based implementation of [`peek`](Peekable::peek)
3227    /// and [`peek_mut`](Peekable::peek_mut).
3228    fn poll_peek_mut(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<&mut S::Item>> {
3229        let mut this = self.project();
3230
3231        match this.peeked {
3232            Some(v) => Poll::Ready(v.as_mut()),
3233            None => {
3234                let peeked = ready!(this.stream.as_mut().poll_next(cx));
3235                Poll::Ready(this.peeked.insert(peeked).as_mut())
3236            }
3237        }
3238    }
3239}
3240
3241impl<S: Stream> Stream for Peekable<S> {
3242    type Item = S::Item;
3243
3244    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3245        let this = self.project();
3246        match this.peeked.take() {
3247            Some(v) => Poll::Ready(v),
3248            None => this.stream.poll_next(cx),
3249        }
3250    }
3251}
3252
3253/// Future for the [`Peekable::peek()`] method.
3254#[must_use = "futures do nothing unless you `.await` or poll them"]
3255pub struct Peek<'peek, S: Stream> {
3256    state: Option<Pin<&'peek mut Peekable<S>>>,
3257}
3258
3259impl<S: Stream + fmt::Debug> fmt::Debug for Peek<'_, S>
3260where
3261    S::Item: fmt::Debug,
3262{
3263    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3264        f.debug_struct("Peek").finish_non_exhaustive()
3265    }
3266}
3267
3268impl<'peek, S: Stream> Future for Peek<'peek, S> {
3269    type Output = Option<&'peek S::Item>;
3270
3271    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3272        poll_peek_mut(&mut self.get_mut().state, cx).map(|peeked| peeked.map(|v| &*v))
3273    }
3274}
3275
3276/// Future for the [`Peekable::peek_mut()`] method.
3277#[must_use = "futures do nothing unless you `.await` or poll them"]
3278pub struct PeekMut<'peek, S: Stream> {
3279    state: Option<Pin<&'peek mut Peekable<S>>>,
3280}
3281
3282impl<S: Stream + fmt::Debug> fmt::Debug for PeekMut<'_, S>
3283where
3284    S::Item: fmt::Debug,
3285{
3286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3287        f.debug_struct("PeekMut").finish_non_exhaustive()
3288    }
3289}
3290
3291impl<'peek, S: Stream> Future for PeekMut<'peek, S> {
3292    type Output = Option<&'peek mut S::Item>;
3293
3294    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3295        poll_peek_mut(&mut self.get_mut().state, cx)
3296    }
3297}
3298
3299fn poll_peek_mut<'peek, S: Stream>(
3300    state: &mut Option<Pin<&'peek mut Peekable<S>>>,
3301    cx: &mut Context<'_>,
3302) -> Poll<Option<&'peek mut S::Item>> {
3303    match state {
3304        Some(peekable) => {
3305            ready!(peekable.as_mut().poll_peek_mut(cx));
3306            state.take().unwrap().poll_peek_mut(cx)
3307        }
3308        None => panic!("polled after completion"),
3309    }
3310}
3311
3312pin_project! {
3313    /// Stream for the [`StreamExt::inspect()`] method.
3314    #[derive(Clone, Debug)]
3315    #[must_use = "streams do nothing unless polled"]
3316    pub struct Inspect<S, F> {
3317        #[pin]
3318        stream: S,
3319        f: F,
3320    }
3321}
3322
3323impl<S, F> Stream for Inspect<S, F>
3324where
3325    S: Stream,
3326    F: FnMut(&S::Item),
3327{
3328    type Item = S::Item;
3329
3330    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3331        let mut this = self.project();
3332        let next = ready!(this.stream.as_mut().poll_next(cx));
3333        if let Some(x) = &next {
3334            (this.f)(x);
3335        }
3336        Poll::Ready(next)
3337    }
3338}
3339
3340/// Future for the [`StreamExt::nth()`] method.
3341#[derive(Debug)]
3342#[must_use = "futures do nothing unless you `.await` or poll them"]
3343pub struct NthFuture<'a, S: ?Sized> {
3344    stream: &'a mut S,
3345    n: usize,
3346}
3347
3348impl<S: Unpin + ?Sized> Unpin for NthFuture<'_, S> {}
3349
3350impl<S> Future for NthFuture<'_, S>
3351where
3352    S: Stream + Unpin + ?Sized,
3353{
3354    type Output = Option<S::Item>;
3355
3356    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3357        loop {
3358            match ready!(self.stream.poll_next(cx)) {
3359                Some(v) => match self.n {
3360                    0 => return Poll::Ready(Some(v)),
3361                    _ => self.n -= 1,
3362                },
3363                None => return Poll::Ready(None),
3364            }
3365        }
3366    }
3367}
3368
3369pin_project! {
3370    /// Future for the [`StreamExt::last()`] method.
3371    #[derive(Debug)]
3372    #[must_use = "futures do nothing unless you `.await` or poll them"]
3373    pub struct LastFuture<S: Stream> {
3374        #[pin]
3375        stream: S,
3376        last: Option<S::Item>,
3377    }
3378}
3379
3380impl<S: Stream> Future for LastFuture<S> {
3381    type Output = Option<S::Item>;
3382
3383    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3384        let mut this = self.project();
3385        loop {
3386            match ready!(this.stream.as_mut().poll_next(cx)) {
3387                Some(new) => *this.last = Some(new),
3388                None => return Poll::Ready(this.last.take()),
3389            }
3390        }
3391    }
3392}
3393
3394/// Future for the [`StreamExt::find()`] method.
3395#[derive(Debug)]
3396#[must_use = "futures do nothing unless you `.await` or poll them"]
3397pub struct FindFuture<'a, S: ?Sized, P> {
3398    stream: &'a mut S,
3399    predicate: P,
3400}
3401
3402impl<S: Unpin + ?Sized, P> Unpin for FindFuture<'_, S, P> {}
3403
3404impl<S, P> Future for FindFuture<'_, S, P>
3405where
3406    S: Stream + Unpin + ?Sized,
3407    P: FnMut(&S::Item) -> bool,
3408{
3409    type Output = Option<S::Item>;
3410
3411    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3412        loop {
3413            match ready!(self.stream.poll_next(cx)) {
3414                Some(v) if (&mut self.predicate)(&v) => return Poll::Ready(Some(v)),
3415                Some(_) => {}
3416                None => return Poll::Ready(None),
3417            }
3418        }
3419    }
3420}
3421
3422/// Future for the [`StreamExt::find_map()`] method.
3423#[derive(Debug)]
3424#[must_use = "futures do nothing unless you `.await` or poll them"]
3425pub struct FindMapFuture<'a, S: ?Sized, F> {
3426    stream: &'a mut S,
3427    f: F,
3428}
3429
3430impl<S: Unpin + ?Sized, F> Unpin for FindMapFuture<'_, S, F> {}
3431
3432impl<S, B, F> Future for FindMapFuture<'_, S, F>
3433where
3434    S: Stream + Unpin + ?Sized,
3435    F: FnMut(S::Item) -> Option<B>,
3436{
3437    type Output = Option<B>;
3438
3439    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3440        loop {
3441            match ready!(self.stream.poll_next(cx)) {
3442                Some(v) => {
3443                    if let Some(v) = (&mut self.f)(v) {
3444                        return Poll::Ready(Some(v));
3445                    }
3446                }
3447                None => return Poll::Ready(None),
3448            }
3449        }
3450    }
3451}
3452
3453/// Future for the [`StreamExt::position()`] method.
3454#[derive(Debug)]
3455#[must_use = "futures do nothing unless you `.await` or poll them"]
3456pub struct PositionFuture<'a, S: ?Sized, P> {
3457    stream: &'a mut S,
3458    predicate: P,
3459    index: usize,
3460}
3461
3462impl<S: Unpin + ?Sized, P> Unpin for PositionFuture<'_, S, P> {}
3463
3464impl<S, P> Future for PositionFuture<'_, S, P>
3465where
3466    S: Stream + Unpin + ?Sized,
3467    P: FnMut(S::Item) -> bool,
3468{
3469    type Output = Option<usize>;
3470
3471    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3472        loop {
3473            match ready!(self.stream.poll_next(cx)) {
3474                Some(v) => {
3475                    if (&mut self.predicate)(v) {
3476                        return Poll::Ready(Some(self.index));
3477                    } else {
3478                        self.index += 1;
3479                    }
3480                }
3481                None => return Poll::Ready(None),
3482            }
3483        }
3484    }
3485}
3486
3487/// Future for the [`StreamExt::all()`] method.
3488#[derive(Debug)]
3489#[must_use = "futures do nothing unless you `.await` or poll them"]
3490pub struct AllFuture<'a, S: ?Sized, P> {
3491    stream: &'a mut S,
3492    predicate: P,
3493}
3494
3495impl<S: Unpin + ?Sized, P> Unpin for AllFuture<'_, S, P> {}
3496
3497impl<S, P> Future for AllFuture<'_, S, P>
3498where
3499    S: Stream + Unpin + ?Sized,
3500    P: FnMut(S::Item) -> bool,
3501{
3502    type Output = bool;
3503
3504    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3505        loop {
3506            match ready!(self.stream.poll_next(cx)) {
3507                Some(v) => {
3508                    if !(&mut self.predicate)(v) {
3509                        return Poll::Ready(false);
3510                    }
3511                }
3512                None => return Poll::Ready(true),
3513            }
3514        }
3515    }
3516}
3517
3518/// Future for the [`StreamExt::any()`] method.
3519#[derive(Debug)]
3520#[must_use = "futures do nothing unless you `.await` or poll them"]
3521pub struct AnyFuture<'a, S: ?Sized, P> {
3522    stream: &'a mut S,
3523    predicate: P,
3524}
3525
3526impl<S: Unpin + ?Sized, P> Unpin for AnyFuture<'_, S, P> {}
3527
3528impl<S, P> Future for AnyFuture<'_, S, P>
3529where
3530    S: Stream + Unpin + ?Sized,
3531    P: FnMut(S::Item) -> bool,
3532{
3533    type Output = bool;
3534
3535    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3536        loop {
3537            match ready!(self.stream.poll_next(cx)) {
3538                Some(v) => {
3539                    if (&mut self.predicate)(v) {
3540                        return Poll::Ready(true);
3541                    }
3542                }
3543                None => return Poll::Ready(false),
3544            }
3545        }
3546    }
3547}
3548
3549pin_project! {
3550    /// Future for the [`StreamExt::for_each()`] method.
3551    #[derive(Debug)]
3552    #[must_use = "futures do nothing unless you `.await` or poll them"]
3553    pub struct ForEachFuture<S, F> {
3554        #[pin]
3555        stream: S,
3556        f: F,
3557    }
3558}
3559
3560impl<S, F> Future for ForEachFuture<S, F>
3561where
3562    S: Stream,
3563    F: FnMut(S::Item),
3564{
3565    type Output = ();
3566
3567    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3568        let mut this = self.project();
3569        loop {
3570            match ready!(this.stream.as_mut().poll_next(cx)) {
3571                Some(v) => (this.f)(v),
3572                None => return Poll::Ready(()),
3573            }
3574        }
3575    }
3576}
3577
3578/// Future for the [`StreamExt::try_for_each()`] method.
3579#[derive(Debug)]
3580#[must_use = "futures do nothing unless you `.await` or poll them"]
3581pub struct TryForEachFuture<'a, S: ?Sized, F> {
3582    stream: &'a mut S,
3583    f: F,
3584}
3585
3586impl<S: Unpin + ?Sized, F> Unpin for TryForEachFuture<'_, S, F> {}
3587
3588impl<S, F, E> Future for TryForEachFuture<'_, S, F>
3589where
3590    S: Stream + Unpin + ?Sized,
3591    F: FnMut(S::Item) -> Result<(), E>,
3592{
3593    type Output = Result<(), E>;
3594
3595    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3596        loop {
3597            match ready!(self.stream.poll_next(cx)) {
3598                None => return Poll::Ready(Ok(())),
3599                Some(v) => (&mut self.f)(v)?,
3600            }
3601        }
3602    }
3603}
3604
3605pin_project! {
3606    /// Stream for the [`StreamExt::zip()`] method.
3607    #[derive(Clone, Debug)]
3608    #[must_use = "streams do nothing unless polled"]
3609    pub struct Zip<A: Stream, B> {
3610        item_slot: Option<A::Item>,
3611        #[pin]
3612        first: A,
3613        #[pin]
3614        second: B,
3615    }
3616}
3617
3618impl<A: Stream, B: Stream> Stream for Zip<A, B> {
3619    type Item = (A::Item, B::Item);
3620
3621    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3622        let this = self.project();
3623
3624        if this.item_slot.is_none() {
3625            match this.first.poll_next(cx) {
3626                Poll::Pending => return Poll::Pending,
3627                Poll::Ready(None) => return Poll::Ready(None),
3628                Poll::Ready(Some(item)) => *this.item_slot = Some(item),
3629            }
3630        }
3631
3632        let second_item = ready!(this.second.poll_next(cx));
3633        let first_item = this.item_slot.take().unwrap();
3634        Poll::Ready(second_item.map(|second_item| (first_item, second_item)))
3635    }
3636}
3637
3638pin_project! {
3639    /// Future for the [`StreamExt::unzip()`] method.
3640    #[derive(Debug)]
3641    #[must_use = "futures do nothing unless you `.await` or poll them"]
3642    pub struct UnzipFuture<S, FromA, FromB> {
3643        #[pin]
3644        stream: S,
3645        res: Option<(FromA, FromB)>,
3646    }
3647}
3648
3649impl<S, A, B, FromA, FromB> Future for UnzipFuture<S, FromA, FromB>
3650where
3651    S: Stream<Item = (A, B)>,
3652    FromA: Default + Extend<A>,
3653    FromB: Default + Extend<B>,
3654{
3655    type Output = (FromA, FromB);
3656
3657    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3658        let mut this = self.project();
3659
3660        loop {
3661            match ready!(this.stream.as_mut().poll_next(cx)) {
3662                Some((a, b)) => {
3663                    let res = this.res.as_mut().unwrap();
3664                    res.0.extend(Some(a));
3665                    res.1.extend(Some(b));
3666                }
3667                None => return Poll::Ready(this.res.take().unwrap()),
3668            }
3669        }
3670    }
3671}
3672
3673/// Stream for the [`StreamExt::drain()`] method.
3674#[derive(Debug)]
3675#[must_use = "streams do nothing unless polled"]
3676pub struct Drain<'a, S: ?Sized> {
3677    stream: &'a mut S,
3678}
3679
3680impl<S: Unpin + ?Sized> Unpin for Drain<'_, S> {}
3681
3682impl<'a, S: Unpin + ?Sized> Drain<'a, S> {
3683    /// Get a reference to the underlying stream.
3684    ///
3685    /// ## Examples
3686    ///
3687    /// ```
3688    /// use futures_lite::{prelude::*, stream};
3689    ///
3690    /// # spin_on::spin_on(async {
3691    /// let mut s = stream::iter(vec![1, 2, 3]);
3692    /// let s2 = s.drain();
3693    ///
3694    /// let inner = s2.get_ref();
3695    /// // s and inner are the same.
3696    /// # });
3697    /// ```
3698    pub fn get_ref(&self) -> &S {
3699        &self.stream
3700    }
3701
3702    /// Get a mutable reference to the underlying stream.
3703    ///
3704    /// ## Examples
3705    ///
3706    /// ```
3707    /// use futures_lite::{prelude::*, stream};
3708    ///
3709    /// # spin_on::spin_on(async {
3710    /// let mut s = stream::iter(vec![1, 2, 3]);
3711    /// let mut s2 = s.drain();
3712    ///
3713    /// let inner = s2.get_mut();
3714    /// assert_eq!(inner.collect::<Vec<_>>().await, vec![1, 2, 3]);
3715    /// # });
3716    /// ```
3717    pub fn get_mut(&mut self) -> &mut S {
3718        &mut self.stream
3719    }
3720
3721    /// Consume this stream and get the underlying stream.
3722    ///
3723    /// ## Examples
3724    ///
3725    /// ```
3726    /// use futures_lite::{prelude::*, stream};
3727    ///
3728    /// # spin_on::spin_on(async {
3729    /// let mut s = stream::iter(vec![1, 2, 3]);
3730    /// let mut s2 = s.drain();
3731    ///
3732    /// let inner = s2.into_inner();
3733    /// assert_eq!(inner.collect::<Vec<_>>().await, vec![1, 2, 3]);
3734    /// # });
3735    /// ```
3736    pub fn into_inner(self) -> &'a mut S {
3737        self.stream
3738    }
3739}
3740
3741impl<S: Stream + Unpin + ?Sized> Stream for Drain<'_, S> {
3742    type Item = S::Item;
3743
3744    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3745        match self.stream.poll_next(cx) {
3746            Poll::Ready(x) => Poll::Ready(x),
3747            Poll::Pending => Poll::Ready(None),
3748        }
3749    }
3750
3751    fn size_hint(&self) -> (usize, Option<usize>) {
3752        let (_, hi) = self.stream.size_hint();
3753        (0, hi)
3754    }
3755}