Skip to main content

futures_util/future/future/
mod.rs

1//! Futures
2//!
3//! This module contains a number of functions for working with `Future`s,
4//! including the `FutureExt` trait which adds methods to `Future` types.
5
6use crate::fns::{inspect_fn, into_fn, ok_fn, InspectFn, IntoFn, OkFn};
7use crate::future::{assert_future, Either};
8use crate::never::Never;
9use crate::stream::assert_stream;
10#[cfg(feature = "alloc")]
11use alloc::boxed::Box;
12use core::pin::pin;
13use core::pin::Pin;
14#[cfg(feature = "alloc")]
15use futures_core::future::{BoxFuture, LocalBoxFuture};
16use futures_core::{
17    future::Future,
18    stream::Stream,
19    task::{Context, Poll},
20};
21
22// Combinators
23
24mod flatten;
25mod fuse;
26mod map;
27
28delegate_all!(
29    /// Future for the [`flatten`](super::FutureExt::flatten) method.
30    Flatten<F>(
31        flatten::Flatten<F, <F as Future>::Output>
32    ): Debug + Future + FusedFuture + New[|x: F| flatten::Flatten::new(x)]
33    where F: Future
34);
35
36delegate_all!(
37    /// Stream for the [`flatten_stream`](FutureExt::flatten_stream) method.
38    FlattenStream<F>(
39        flatten::Flatten<F, <F as Future>::Output>
40    ): Debug + Sink + Stream + FusedStream + New[|x: F| flatten::Flatten::new(x)]
41    where F: Future
42);
43
44#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
45pub use fuse::Fuse;
46
47delegate_all!(
48    /// Future for the [`map`](super::FutureExt::map) method.
49    Map<Fut, F>(
50        map::Map<Fut, F>
51    ): Debug + Future + FusedFuture + New[|x: Fut, f: F| map::Map::new(x, f)]
52);
53
54delegate_all!(
55    /// Stream for the [`into_stream`](FutureExt::into_stream) method.
56    IntoStream<F>(
57        crate::stream::Once<F>
58    ): Debug + Stream + FusedStream + New[|x: F| crate::stream::Once::new(x)]
59);
60
61delegate_all!(
62    /// Future for the [`map_into`](FutureExt::map_into) combinator.
63    MapInto<Fut, T>(
64        Map<Fut, IntoFn<T>>
65    ): Debug + Future + FusedFuture + New[|x: Fut| Map::new(x, into_fn())]
66);
67
68delegate_all!(
69    /// Future for the [`then`](FutureExt::then) method.
70    Then<Fut1, Fut2, F>(
71        flatten::Flatten<Map<Fut1, F>, Fut2>
72    ): Debug + Future + FusedFuture + New[|x: Fut1, y: F| flatten::Flatten::new(Map::new(x, y))]
73);
74
75delegate_all!(
76    /// Future for the [`inspect`](FutureExt::inspect) method.
77    Inspect<Fut, F>(
78        map::Map<Fut, InspectFn<F>>
79    ): Debug + Future + FusedFuture + New[|x: Fut, f: F| map::Map::new(x, inspect_fn(f))]
80);
81
82delegate_all!(
83    /// Future for the [`never_error`](super::FutureExt::never_error) combinator.
84    NeverError<Fut>(
85        Map<Fut, OkFn<Never>>
86    ): Debug + Future + FusedFuture + New[|x: Fut| Map::new(x, ok_fn())]
87);
88
89delegate_all!(
90    /// Future for the [`unit_error`](super::FutureExt::unit_error) combinator.
91    UnitError<Fut>(
92        Map<Fut, OkFn<()>>
93    ): Debug + Future + FusedFuture + New[|x: Fut| Map::new(x, ok_fn())]
94);
95
96#[cfg(feature = "std")]
97mod catch_unwind;
98#[cfg(feature = "std")]
99#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
100pub use self::catch_unwind::CatchUnwind;
101
102#[cfg(feature = "channel")]
103#[cfg_attr(docsrs, doc(cfg(feature = "channel")))]
104#[cfg(feature = "std")]
105mod remote_handle;
106#[cfg(feature = "channel")]
107#[cfg_attr(docsrs, doc(cfg(feature = "channel")))]
108#[cfg(feature = "std")]
109#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
110pub use self::remote_handle::{Remote, RemoteHandle};
111
112#[cfg(any(feature = "std", all(feature = "alloc", feature = "spin")))]
113mod shared;
114#[cfg(any(feature = "std", all(feature = "alloc", feature = "spin")))]
115pub use self::shared::{Shared, WeakShared};
116
117impl<T: ?Sized> FutureExt for T where T: Future {}
118
119/// An extension trait for `Future`s that provides a variety of convenient
120/// adapters.
121pub trait FutureExt: Future {
122    /// Map this future's output to a different type, returning a new future of
123    /// the resulting type.
124    ///
125    /// This function is similar to the `Option::map` or `Iterator::map` where
126    /// it will change the type of the underlying future. This is useful to
127    /// chain along a computation once a future has been resolved.
128    ///
129    /// Note that this function consumes the receiving future and returns a
130    /// wrapped version of it, similar to the existing `map` methods in the
131    /// standard library.
132    ///
133    /// # Examples
134    ///
135    /// ```
136    /// # futures::executor::block_on(async {
137    /// use futures::future::FutureExt;
138    ///
139    /// let future = async { 1 };
140    /// let new_future = future.map(|x| x + 3);
141    /// assert_eq!(new_future.await, 4);
142    /// # });
143    /// ```
144    fn map<U, F>(self, f: F) -> Map<Self, F>
145    where
146        F: FnOnce(Self::Output) -> U,
147        Self: Sized,
148    {
149        assert_future::<U, _>(Map::new(self, f))
150    }
151
152    /// Map this future's output to a different type, returning a new future of
153    /// the resulting type.
154    ///
155    /// This function is equivalent to calling `map(Into::into)` but allows naming
156    /// the return type.
157    fn map_into<U>(self) -> MapInto<Self, U>
158    where
159        Self::Output: Into<U>,
160        Self: Sized,
161    {
162        assert_future::<U, _>(MapInto::new(self))
163    }
164
165    /// Chain on a computation for when a future finished, passing the result of
166    /// the future to the provided closure `f`.
167    ///
168    /// The returned value of the closure must implement the `Future` trait
169    /// and can represent some more work to be done before the composed future
170    /// is finished.
171    ///
172    /// The closure `f` is only run *after* successful completion of the `self`
173    /// future.
174    ///
175    /// Note that this function consumes the receiving future and returns a
176    /// wrapped version of it.
177    ///
178    /// # Examples
179    ///
180    /// ```
181    /// # futures::executor::block_on(async {
182    /// use futures::future::FutureExt;
183    ///
184    /// let future_of_1 = async { 1 };
185    /// let future_of_4 = future_of_1.then(|x| async move { x + 3 });
186    /// assert_eq!(future_of_4.await, 4);
187    /// # });
188    /// ```
189    fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
190    where
191        F: FnOnce(Self::Output) -> Fut,
192        Fut: Future,
193        Self: Sized,
194    {
195        assert_future::<Fut::Output, _>(Then::new(self, f))
196    }
197
198    /// Wrap this future in an `Either` future, making it the left-hand variant
199    /// of that `Either`.
200    ///
201    /// This can be used in combination with the `right_future` method to write `if`
202    /// statements that evaluate to different futures in different branches.
203    ///
204    /// # Examples
205    ///
206    /// ```
207    /// # futures::executor::block_on(async {
208    /// use futures::future::FutureExt;
209    ///
210    /// let x = 6;
211    /// let future = if x < 10 {
212    ///     async { true }.left_future()
213    /// } else {
214    ///     async { false }.right_future()
215    /// };
216    ///
217    /// assert_eq!(future.await, true);
218    /// # });
219    /// ```
220    fn left_future<B>(self) -> Either<Self, B>
221    where
222        B: Future<Output = Self::Output>,
223        Self: Sized,
224    {
225        assert_future::<Self::Output, _>(Either::Left(self))
226    }
227
228    /// Wrap this future in an `Either` future, making it the right-hand variant
229    /// of that `Either`.
230    ///
231    /// This can be used in combination with the `left_future` method to write `if`
232    /// statements that evaluate to different futures in different branches.
233    ///
234    /// # Examples
235    ///
236    /// ```
237    /// # futures::executor::block_on(async {
238    /// use futures::future::FutureExt;
239    ///
240    /// let x = 6;
241    /// let future = if x > 10 {
242    ///     async { true }.left_future()
243    /// } else {
244    ///     async { false }.right_future()
245    /// };
246    ///
247    /// assert_eq!(future.await, false);
248    /// # });
249    /// ```
250    fn right_future<A>(self) -> Either<A, Self>
251    where
252        A: Future<Output = Self::Output>,
253        Self: Sized,
254    {
255        assert_future::<Self::Output, _>(Either::Right(self))
256    }
257
258    /// Convert this future into a single element stream.
259    ///
260    /// The returned stream contains single success if this future resolves to
261    /// success or single error if this future resolves into error.
262    ///
263    /// # Examples
264    ///
265    /// ```
266    /// # futures::executor::block_on(async {
267    /// use futures::future::FutureExt;
268    /// use futures::stream::StreamExt;
269    ///
270    /// let future = async { 17 };
271    /// let stream = future.into_stream();
272    /// let collected: Vec<_> = stream.collect().await;
273    /// assert_eq!(collected, vec![17]);
274    /// # });
275    /// ```
276    fn into_stream(self) -> IntoStream<Self>
277    where
278        Self: Sized,
279    {
280        assert_stream::<Self::Output, _>(IntoStream::new(self))
281    }
282
283    /// Flatten the execution of this future when the output of this
284    /// future is itself another future.
285    ///
286    /// This can be useful when combining futures together to flatten the
287    /// computation out the final result.
288    ///
289    /// This method is roughly equivalent to `self.then(|x| x)`.
290    ///
291    /// Note that this function consumes the receiving future and returns a
292    /// wrapped version of it.
293    ///
294    /// # Examples
295    ///
296    /// ```
297    /// # futures::executor::block_on(async {
298    /// use futures::future::FutureExt;
299    ///
300    /// let nested_future = async { async { 1 } };
301    /// let future = nested_future.flatten();
302    /// assert_eq!(future.await, 1);
303    /// # });
304    /// ```
305    fn flatten(self) -> Flatten<Self>
306    where
307        Self::Output: Future,
308        Self: Sized,
309    {
310        let f = Flatten::new(self);
311        assert_future::<<<Self as Future>::Output as Future>::Output, _>(f)
312    }
313
314    /// Flatten the execution of this future when the successful result of this
315    /// future is a stream.
316    ///
317    /// This can be useful when stream initialization is deferred, and it is
318    /// convenient to work with that stream as if stream was available at the
319    /// call site.
320    ///
321    /// Note that this function consumes this future and returns a wrapped
322    /// version of it.
323    ///
324    /// # Examples
325    ///
326    /// ```
327    /// # futures::executor::block_on(async {
328    /// use futures::future::FutureExt;
329    /// use futures::stream::{self, StreamExt};
330    ///
331    /// let stream_items = vec![17, 18, 19];
332    /// let future_of_a_stream = async { stream::iter(stream_items) };
333    ///
334    /// let stream = future_of_a_stream.flatten_stream();
335    /// let list: Vec<_> = stream.collect().await;
336    /// assert_eq!(list, vec![17, 18, 19]);
337    /// # });
338    /// ```
339    fn flatten_stream(self) -> FlattenStream<Self>
340    where
341        Self::Output: Stream,
342        Self: Sized,
343    {
344        assert_stream::<<Self::Output as Stream>::Item, _>(FlattenStream::new(self))
345    }
346
347    /// Fuse a future such that `poll` will never again be called once it has
348    /// completed. This method can be used to turn any `Future` into a
349    /// `FusedFuture`.
350    ///
351    /// Normally, once a future has returned `Poll::Ready` from `poll`,
352    /// any further calls could exhibit bad behavior such as blocking
353    /// forever, panicking, never returning, etc. If it is known that `poll`
354    /// may be called too often then this method can be used to ensure that it
355    /// has defined semantics.
356    ///
357    /// If a `fuse`d future is `poll`ed after having returned `Poll::Ready`
358    /// previously, it will return `Poll::Pending`, from `poll` again (and will
359    /// continue to do so for all future calls to `poll`).
360    ///
361    /// This combinator will drop the underlying future as soon as it has been
362    /// completed to ensure resources are reclaimed as soon as possible.
363    fn fuse(self) -> Fuse<Self>
364    where
365        Self: Sized,
366    {
367        let f = Fuse::new(self);
368        assert_future::<Self::Output, _>(f)
369    }
370
371    /// Do something with the output of a future before passing it on.
372    ///
373    /// When using futures, you'll often chain several of them together.  While
374    /// working on such code, you might want to check out what's happening at
375    /// various parts in the pipeline, without consuming the intermediate
376    /// value. To do that, insert a call to `inspect`.
377    ///
378    /// # Examples
379    ///
380    /// ```
381    /// # futures::executor::block_on(async {
382    /// use futures::future::FutureExt;
383    ///
384    /// let future = async { 1 };
385    /// let new_future = future.inspect(|&x| println!("about to resolve: {}", x));
386    /// assert_eq!(new_future.await, 1);
387    /// # });
388    /// ```
389    fn inspect<F>(self, f: F) -> Inspect<Self, F>
390    where
391        F: FnOnce(&Self::Output),
392        Self: Sized,
393    {
394        assert_future::<Self::Output, _>(Inspect::new(self, f))
395    }
396
397    /// Catches unwinding panics while polling the future.
398    ///
399    /// In general, panics within a future can propagate all the way out to the
400    /// task level. This combinator makes it possible to halt unwinding within
401    /// the future itself. It's most commonly used within task executors. It's
402    /// not recommended to use this for error handling.
403    ///
404    /// Note that this method requires the `UnwindSafe` bound from the standard
405    /// library. This isn't always applied automatically, and the standard
406    /// library provides an `AssertUnwindSafe` wrapper type to apply it
407    /// after-the fact. To assist using this method, the `Future` trait is also
408    /// implemented for `AssertUnwindSafe<F>` where `F` implements `Future`.
409    ///
410    /// This method is only available when the `std` feature of this
411    /// library is activated, and it is activated by default.
412    ///
413    /// # Examples
414    ///
415    /// ```
416    /// # futures::executor::block_on(async {
417    /// use futures::future::{self, FutureExt, Ready};
418    ///
419    /// let future = future::ready(2);
420    /// assert!(future.catch_unwind().await.is_ok());
421    ///
422    /// let future = future::lazy(|_| -> Ready<i32> {
423    ///     unimplemented!()
424    /// });
425    /// assert!(future.catch_unwind().await.is_err());
426    /// # });
427    /// ```
428    #[cfg(feature = "std")]
429    fn catch_unwind(self) -> CatchUnwind<Self>
430    where
431        Self: Sized + ::std::panic::UnwindSafe,
432    {
433        assert_future::<Result<Self::Output, Box<dyn std::any::Any + Send>>, _>(CatchUnwind::new(
434            self,
435        ))
436    }
437
438    /// Create a cloneable handle to this future where all handles will resolve
439    /// to the same result.
440    ///
441    /// The `shared` combinator method provides a method to convert any future
442    /// into a cloneable future. It enables a future to be polled by multiple
443    /// threads.
444    ///
445    /// This method is only available when the `std` or 'spin' feature of this
446    /// library is activated, and it is activated by default.
447    ///
448    /// # Examples
449    ///
450    /// ```
451    /// # futures::executor::block_on(async {
452    /// use futures::future::FutureExt;
453    ///
454    /// let future = async { 6 };
455    /// let shared1 = future.shared();
456    /// let shared2 = shared1.clone();
457    ///
458    /// assert_eq!(6, shared1.await);
459    /// assert_eq!(6, shared2.await);
460    /// # });
461    /// ```
462    ///
463    /// ```
464    /// # futures::executor::block_on(async {
465    /// use futures::future::FutureExt;
466    /// use futures::executor::block_on;
467    /// use std::thread;
468    ///
469    /// let future = async { 6 };
470    /// let shared1 = future.shared();
471    /// let shared2 = shared1.clone();
472    /// let join_handle = thread::spawn(move || {
473    ///     assert_eq!(6, block_on(shared2));
474    /// });
475    /// assert_eq!(6, shared1.await);
476    /// join_handle.join().unwrap();
477    /// # });
478    /// ```
479    #[cfg(any(feature = "std", all(feature = "alloc", feature = "spin")))]
480    fn shared(self) -> Shared<Self>
481    where
482        Self: Sized,
483        Self::Output: Clone,
484    {
485        assert_future::<Self::Output, _>(Shared::new(self))
486    }
487
488    /// Turn this future into a future that yields `()` on completion and sends
489    /// its output to another future on a separate task.
490    ///
491    /// This can be used with spawning executors to easily retrieve the result
492    /// of a future executing on a separate task or thread.
493    ///
494    /// This method is only available when the `std` feature of this
495    /// library is activated, and it is activated by default.
496    #[cfg(feature = "channel")]
497    #[cfg_attr(docsrs, doc(cfg(feature = "channel")))]
498    #[cfg(feature = "std")]
499    fn remote_handle(self) -> (Remote<Self>, RemoteHandle<Self::Output>)
500    where
501        Self: Sized,
502    {
503        let (wrapped, handle) = remote_handle::remote_handle(self);
504        (assert_future::<(), _>(wrapped), handle)
505    }
506
507    /// Wrap the future in a Box, pinning it.
508    ///
509    /// This method is only available when the `std` or `alloc` feature of this
510    /// library is activated, and it is activated by default.
511    #[cfg(feature = "alloc")]
512    fn boxed<'a>(self) -> BoxFuture<'a, Self::Output>
513    where
514        Self: Sized + Send + 'a,
515    {
516        assert_future::<Self::Output, _>(Box::pin(self))
517    }
518
519    /// Wrap the future in a Box, pinning it.
520    ///
521    /// Similar to `boxed`, but without the `Send` requirement.
522    ///
523    /// This method is only available when the `std` or `alloc` feature of this
524    /// library is activated, and it is activated by default.
525    #[cfg(feature = "alloc")]
526    fn boxed_local<'a>(self) -> LocalBoxFuture<'a, Self::Output>
527    where
528        Self: Sized + 'a,
529    {
530        assert_future::<Self::Output, _>(Box::pin(self))
531    }
532
533    /// Turns a [`Future<Output = T>`](Future) into a
534    /// [`TryFuture<Ok = T, Error = ()`>](futures_core::future::TryFuture).
535    fn unit_error(self) -> UnitError<Self>
536    where
537        Self: Sized,
538    {
539        assert_future::<Result<Self::Output, ()>, _>(UnitError::new(self))
540    }
541
542    /// Turns a [`Future<Output = T>`](Future) into a
543    /// [`TryFuture<Ok = T, Error = Never`>](futures_core::future::TryFuture).
544    fn never_error(self) -> NeverError<Self>
545    where
546        Self: Sized,
547    {
548        assert_future::<Result<Self::Output, Never>, _>(NeverError::new(self))
549    }
550
551    /// A convenience for calling `Future::poll` on `Unpin` future types.
552    fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
553    where
554        Self: Unpin,
555    {
556        Pin::new(self).poll(cx)
557    }
558
559    /// Evaluates and consumes the future, returning the resulting output if
560    /// the future is ready after the first call to `Future::poll`.
561    ///
562    /// If `poll` instead returns `Poll::Pending`, `None` is returned.
563    ///
564    /// This method is useful in cases where immediacy is more important than
565    /// waiting for a result. It is also convenient for quickly obtaining
566    /// the value of a future that is known to always resolve immediately.
567    ///
568    /// # Examples
569    ///
570    /// ```
571    /// # use futures::prelude::*;
572    /// use futures::{future::ready, future::pending};
573    /// let future_ready = ready("foobar");
574    /// let future_pending = pending::<&'static str>();
575    ///
576    /// assert_eq!(future_ready.now_or_never(), Some("foobar"));
577    /// assert_eq!(future_pending.now_or_never(), None);
578    /// ```
579    ///
580    /// In cases where it is absolutely known that a future should always
581    /// resolve immediately and never return `Poll::Pending`, this method can
582    /// be combined with `expect()`:
583    ///
584    /// ```
585    /// # use futures::{prelude::*, future::ready};
586    /// let future_ready = ready("foobar");
587    ///
588    /// assert_eq!(future_ready.now_or_never().expect("Future not ready"), "foobar");
589    /// ```
590    fn now_or_never(self) -> Option<Self::Output>
591    where
592        Self: Sized,
593    {
594        let noop_waker = crate::task::noop_waker();
595        let mut cx = Context::from_waker(&noop_waker);
596
597        let this = pin!(self);
598        match this.poll(&mut cx) {
599            Poll::Ready(x) => Some(x),
600            _ => None,
601        }
602    }
603}