futures_util/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 core::result;
7
8use futures_core::{Future, IntoFuture, Stream};
9use futures_sink::Sink;
10
11// Primitive futures
12mod empty;
13mod lazy;
14mod poll_fn;
15mod loop_fn;
16pub use self::empty::{empty, Empty};
17pub use self::lazy::{lazy, Lazy};
18pub use self::poll_fn::{poll_fn, PollFn};
19pub use self::loop_fn::{loop_fn, Loop, LoopFn};
20
21// combinators
22mod and_then;
23mod flatten;
24mod flatten_sink;
25mod flatten_stream;
26mod fuse;
27mod into_stream;
28mod join;
29mod map;
30mod map_err;
31mod err_into;
32mod or_else;
33mod select;
34mod then;
35mod inspect;
36mod inspect_err;
37mod recover;
38
39// impl details
40mod chain;
41
42pub use self::and_then::AndThen;
43pub use self::flatten::Flatten;
44pub use self::flatten_sink::FlattenSink;
45pub use self::flatten_stream::FlattenStream;
46pub use self::fuse::Fuse;
47pub use self::into_stream::IntoStream;
48pub use self::join::{Join, Join3, Join4, Join5};
49pub use self::map::Map;
50pub use self::map_err::MapErr;
51pub use self::err_into::ErrInto;
52pub use self::or_else::OrElse;
53pub use self::select::Select;
54pub use self::then::Then;
55pub use self::inspect::Inspect;
56pub use self::inspect_err::InspectErr;
57pub use self::recover::Recover;
58
59pub use either::Either;
60
61if_std! {
62    mod catch_unwind;
63    mod join_all;
64    mod select_all;
65    mod select_ok;
66    mod shared;
67    mod with_executor;
68    pub use self::catch_unwind::CatchUnwind;
69    pub use self::join_all::{join_all, JoinAll};
70    pub use self::select_all::{SelectAll, SelectAllNext, select_all};
71    pub use self::select_ok::{SelectOk, select_ok};
72    pub use self::shared::{Shared, SharedItem, SharedError};
73    pub use self::with_executor::WithExecutor;
74}
75
76impl<T: ?Sized> FutureExt for T where T: Future {}
77
78/// An extension trait for `Future`s that provides a variety of convenient
79/// combinator functions.
80pub trait FutureExt: Future {
81    /// Map this future's result to a different type, returning a new future of
82    /// the resulting type.
83    ///
84    /// This function is similar to the `Option::map` or `Iterator::map` where
85    /// it will change the type of the underlying future. This is useful to
86    /// chain along a computation once a future has been resolved.
87    ///
88    /// The closure provided will only be called if this future is resolved
89    /// successfully. If this future returns an error, panics, or is dropped,
90    /// then the closure provided will never be invoked.
91    ///
92    /// Note that this function consumes the receiving future and returns a
93    /// wrapped version of it, similar to the existing `map` methods in the
94    /// standard library.
95    ///
96    /// # Examples
97    ///
98    /// ```
99    /// # extern crate futures;
100    /// # extern crate futures_executor;
101    /// use futures::prelude::*;
102    /// use futures::future;
103    /// use futures_executor::block_on;
104    ///
105    /// # fn main() {
106    /// let future = future::ok::<u32, u32>(1);
107    /// let new_future = future.map(|x| x + 3);
108    /// assert_eq!(block_on(new_future), Ok(4));
109    /// # }
110    /// ```
111    ///
112    /// Calling `map` on an errored `Future` has no effect:
113    ///
114    /// ```
115    /// # extern crate futures;
116    /// # extern crate futures_executor;
117    /// use futures::prelude::*;
118    /// use futures::future;
119    /// use futures_executor::block_on;
120    ///
121    /// # fn main() {
122    /// let future = future::err::<u32, u32>(1);
123    /// let new_future = future.map(|x| x + 3);
124    /// assert_eq!(block_on(new_future), Err(1));
125    /// # }
126    /// ```
127    fn map<U, F>(self, f: F) -> Map<Self, F>
128        where F: FnOnce(Self::Item) -> U,
129              Self: Sized,
130    {
131        assert_future::<U, Self::Error, _>(map::new(self, f))
132    }
133
134    /// Map this future's error to a different error, returning a new future.
135    ///
136    /// This function is similar to the `Result::map_err` where it will change
137    /// the error type of the underlying future. This is useful for example to
138    /// ensure that futures have the same error type when used with combinators
139    /// like `select` and `join`.
140    ///
141    /// The closure provided will only be called if this future is resolved
142    /// with an error. If this future returns a success, panics, or is
143    /// dropped, then the closure provided will never be invoked.
144    ///
145    /// Note that this function consumes the receiving future and returns a
146    /// wrapped version of it.
147    ///
148    /// # Examples
149    ///
150    /// ```
151    /// # extern crate futures;
152    /// # extern crate futures_executor;
153    /// use futures::future::err;
154    /// use futures::prelude::*;
155    /// use futures_executor::block_on;
156    ///
157    /// # fn main() {
158    /// let future = err::<u32, u32>(1);
159    /// let new_future = future.map_err(|x| x + 3);
160    /// assert_eq!(block_on(new_future), Err(4));
161    /// # }
162    /// ```
163    ///
164    /// Calling `map_err` on a successful `Future` has no effect:
165    ///
166    /// ```
167    /// # extern crate futures;
168    /// # extern crate futures_executor;
169    /// use futures::future::ok;
170    /// use futures::prelude::*;
171    /// use futures_executor::block_on;
172    ///
173    /// # fn main() {
174    /// let future = ok::<u32, u32>(1);
175    /// let new_future = future.map_err(|x| x + 3);
176    /// assert_eq!(block_on(new_future), Ok(1));
177    /// # }
178    /// ```
179    fn map_err<E, F>(self, f: F) -> MapErr<Self, F>
180        where F: FnOnce(Self::Error) -> E,
181              Self: Sized,
182    {
183        assert_future::<Self::Item, E, _>(map_err::new(self, f))
184    }
185
186    /// Map this future's error to a new error type using the `Into` trait.
187    ///
188    /// This function does for futures what `try!` does for `Result`,
189    /// by letting the compiler infer the type of the resulting error.
190    /// Just as `map_err` above, this is useful for example to ensure
191    /// that futures have the same error type when used with
192    /// combinators like `select` and `join`.
193    ///
194    /// Note that this function consumes the receiving future and returns a
195    /// wrapped version of it.
196    ///
197    /// # Examples
198    ///
199    /// ```
200    /// # extern crate futures;
201    /// use futures::prelude::*;
202    /// use futures::future;
203    ///
204    /// # fn main() {
205    /// let future_with_err_u8 = future::err::<(), u8>(1);
206    /// let future_with_err_u32 = future_with_err_u8.err_into::<u32>();
207    /// # }
208    /// ```
209    fn err_into<E>(self) -> ErrInto<Self, E>
210        where Self: Sized,
211              Self::Error: Into<E>
212    {
213        assert_future::<Self::Item, E, _>(err_into::new(self))
214    }
215
216    /// Chain on a computation for when a future finished, passing the result of
217    /// the future to the provided closure `f`.
218    ///
219    /// This function can be used to ensure a computation runs regardless of
220    /// the conclusion of the future. The closure provided will be yielded a
221    /// `Result` once the future is complete.
222    ///
223    /// The returned value of the closure must implement the `IntoFuture` trait
224    /// and can represent some more work to be done before the composed future
225    /// is finished. Note that the `Result` type implements the `IntoFuture`
226    /// trait so it is possible to simply alter the `Result` yielded to the
227    /// closure and return it.
228    ///
229    /// If this future is dropped or panics then the closure `f` will not be
230    /// run.
231    ///
232    /// Note that this function consumes the receiving future and returns a
233    /// wrapped version of it.
234    ///
235    /// # Examples
236    ///
237    /// ```
238    /// # extern crate futures;
239    /// use futures::prelude::*;
240    /// use futures::future;
241    ///
242    /// # fn main() {
243    /// let future_of_1 = future::ok::<u32, u32>(1);
244    /// let future_of_4 = future_of_1.then(|x| {
245    ///     x.map(|y| y + 3)
246    /// });
247    ///
248    /// let future_of_err_1 = future::err::<u32, u32>(1);
249    /// let future_of_4 = future_of_err_1.then(|x| {
250    ///     match x {
251    ///         Ok(_) => panic!("expected an error"),
252    ///         Err(y) => future::ok::<u32, u32>(y + 3),
253    ///     }
254    /// });
255    /// # }
256    /// ```
257    fn then<B, F>(self, f: F) -> Then<Self, B, F>
258        where F: FnOnce(result::Result<Self::Item, Self::Error>) -> B,
259              B: IntoFuture,
260              Self: Sized,
261    {
262        assert_future::<B::Item, B::Error, _>(then::new(self, f))
263    }
264
265    /// Execute another future after this one has resolved successfully.
266    ///
267    /// This function can be used to chain two futures together and ensure that
268    /// the final future isn't resolved until both have finished. The closure
269    /// provided is yielded the successful result of this future and returns
270    /// another value which can be converted into a future.
271    ///
272    /// Note that because `Result` implements the `IntoFuture` trait this method
273    /// can also be useful for chaining fallible and serial computations onto
274    /// the end of one future.
275    ///
276    /// If this future is dropped, panics, or completes with an error then the
277    /// provided closure `f` is never called.
278    ///
279    /// Note that this function consumes the receiving future and returns a
280    /// wrapped version of it.
281    ///
282    /// # Examples
283    ///
284    /// ```
285    /// # extern crate futures;
286    /// use futures::prelude::*;
287    /// use futures::future::{self, FutureResult};
288    ///
289    /// # fn main() {
290    /// let future_of_1 = future::ok::<u32, u32>(1);
291    /// let future_of_4 = future_of_1.and_then(|x| {
292    ///     Ok(x + 3)
293    /// });
294    ///
295    /// let future_of_err_1 = future::err::<u32, u32>(1);
296    /// future_of_err_1.and_then(|_| -> FutureResult<u32, u32> {
297    ///     panic!("should not be called in case of an error");
298    /// });
299    /// # }
300    /// ```
301    fn and_then<B, F>(self, f: F) -> AndThen<Self, B, F>
302        where F: FnOnce(Self::Item) -> B,
303              B: IntoFuture<Error = Self::Error>,
304              Self: Sized,
305    {
306        assert_future::<B::Item, Self::Error, _>(and_then::new(self, f))
307    }
308
309    /// Execute another future if this one resolves with an error.
310    ///
311    /// Return a future that passes along this future's value if it succeeds,
312    /// and otherwise passes the error to the closure `f` and waits for the
313    /// future it returns. The closure may also simply return a value that can
314    /// be converted into a future.
315    ///
316    /// Note that because `Result` implements the `IntoFuture` trait this method
317    /// can also be useful for chaining together fallback computations, where
318    /// when one fails, the next is attempted.
319    ///
320    /// If this future is dropped, panics, or completes successfully then the
321    /// provided closure `f` is never called.
322    ///
323    /// Note that this function consumes the receiving future and returns a
324    /// wrapped version of it.
325    ///
326    /// # Examples
327    ///
328    /// ```
329    /// # extern crate futures;
330    /// use futures::prelude::*;
331    /// use futures::future::{self, FutureResult};
332    ///
333    /// # fn main() {
334    /// let future_of_err_1 = future::err::<u32, u32>(1);
335    /// let future_of_4 = future_of_err_1.or_else(|x| -> Result<u32, u32> {
336    ///     Ok(x + 3)
337    /// });
338    ///
339    /// let future_of_1 = future::ok::<u32, u32>(1);
340    /// future_of_1.or_else(|_| -> FutureResult<u32, u32> {
341    ///     panic!("should not be called in case of success");
342    /// });
343    /// # }
344    /// ```
345    fn or_else<B, F>(self, f: F) -> OrElse<Self, B, F>
346        where F: FnOnce(Self::Error) -> B,
347              B: IntoFuture<Item = Self::Item>,
348              Self: Sized,
349    {
350        assert_future::<Self::Item, B::Error, _>(or_else::new(self, f))
351    }
352
353    /// Waits for either one of two differently-typed futures to complete.
354    ///
355    /// This function will return a new future which awaits for either this or
356    /// the `other` future to complete. The returned future will finish with
357    /// both the value resolved and a future representing the completion of the
358    /// other work.
359    ///
360    /// Note that this function consumes the receiving futures and returns a
361    /// wrapped version of them.
362    ///
363    /// Also note that if both this and the second future have the same
364    /// success/error type you can use the `Either::split` method to
365    /// conveniently extract out the value at the end.
366    ///
367    /// # Examples
368    ///
369    /// ```
370    /// # extern crate futures;
371    /// use futures::prelude::*;
372    /// use futures::future::{self, Either};
373    ///
374    /// // A poor-man's join implemented on top of select
375    ///
376    /// fn join<A, B, E>(a: A, b: B) -> Box<Future<Item=(A::Item, B::Item), Error=E>>
377    ///     where A: Future<Error = E> + 'static,
378    ///           B: Future<Error = E> + 'static,
379    ///           E: 'static,
380    /// {
381    ///     Box::new(a.select(b).then(|res| -> Box<Future<Item=_, Error=_>> {
382    ///         match res {
383    ///             Ok(Either::Left((x, b))) => Box::new(b.map(move |y| (x, y))),
384    ///             Ok(Either::Right((y, a))) => Box::new(a.map(move |x| (x, y))),
385    ///             Err(Either::Left((e, _))) => Box::new(future::err(e)),
386    ///             Err(Either::Right((e, _))) => Box::new(future::err(e)),
387    ///         }
388    ///     }))
389    /// }
390    /// # fn main() {}
391    /// ```
392    fn select<B>(self, other: B) -> Select<Self, B::Future>
393        where B: IntoFuture, Self: Sized
394    {
395        select::new(self, other.into_future())
396    }
397
398    /// Joins the result of two futures, waiting for them both to complete.
399    ///
400    /// This function will return a new future which awaits both this and the
401    /// `other` future to complete. The returned future will finish with a tuple
402    /// of both results.
403    ///
404    /// Both futures must have the same error type, and if either finishes with
405    /// an error then the other will be dropped and that error will be
406    /// returned.
407    ///
408    /// Note that this function consumes the receiving future and returns a
409    /// wrapped version of it.
410    ///
411    /// # Examples
412    ///
413    /// ```
414    /// # extern crate futures;
415    /// # extern crate futures_executor;
416    /// use futures::prelude::*;
417    /// use futures::future;
418    /// use futures_executor::block_on;
419    ///
420    /// # fn main() {
421    /// let a = future::ok::<u32, u32>(1);
422    /// let b = future::ok::<u32, u32>(2);
423    /// let pair = a.join(b);
424    ///
425    /// assert_eq!(block_on(pair), Ok((1, 2)));
426    /// # }
427    /// ```
428    ///
429    /// If one or both of the joined `Future`s is errored, the resulting
430    /// `Future` will be errored:
431    ///
432    /// ```
433    /// # extern crate futures;
434    /// # extern crate futures_executor;
435    /// use futures::prelude::*;
436    /// use futures::future;
437    /// use futures_executor::block_on;
438    ///
439    /// # fn main() {
440    /// let a = future::ok::<u32, u32>(1);
441    /// let b = future::err::<u32, u32>(2);
442    /// let pair = a.join(b);
443    ///
444    /// assert_eq!(block_on(pair), Err(2));
445    /// # }
446    /// ```
447    fn join<B>(self, other: B) -> Join<Self, B::Future>
448        where B: IntoFuture<Error=Self::Error>,
449              Self: Sized,
450    {
451        let f = join::new(self, other.into_future());
452        assert_future::<(Self::Item, B::Item), Self::Error, _>(f)
453    }
454
455    /// Same as `join`, but with more futures.
456    fn join3<B, C>(self, b: B, c: C) -> Join3<Self, B::Future, C::Future>
457        where B: IntoFuture<Error=Self::Error>,
458              C: IntoFuture<Error=Self::Error>,
459              Self: Sized,
460    {
461        join::new3(self, b.into_future(), c.into_future())
462    }
463
464    /// Same as `join`, but with more futures.
465    fn join4<B, C, D>(self, b: B, c: C, d: D)
466                      -> Join4<Self, B::Future, C::Future, D::Future>
467        where B: IntoFuture<Error=Self::Error>,
468              C: IntoFuture<Error=Self::Error>,
469              D: IntoFuture<Error=Self::Error>,
470              Self: Sized,
471    {
472        join::new4(self, b.into_future(), c.into_future(), d.into_future())
473    }
474
475    /// Same as `join`, but with more futures.
476    fn join5<B, C, D, E>(self, b: B, c: C, d: D, e: E)
477                         -> Join5<Self, B::Future, C::Future, D::Future, E::Future>
478        where B: IntoFuture<Error=Self::Error>,
479              C: IntoFuture<Error=Self::Error>,
480              D: IntoFuture<Error=Self::Error>,
481              E: IntoFuture<Error=Self::Error>,
482              Self: Sized,
483    {
484        join::new5(self, b.into_future(), c.into_future(), d.into_future(),
485                   e.into_future())
486    }
487
488    /// Wrap this future in an `Either` future, making it the left-hand variant
489    /// of that `Either`.
490    ///
491    /// This can be used in combination with the `right` method to write `if`
492    /// statements that evaluate to different futures in different branches.
493    ///
494    /// # Examples
495    ///
496    /// ```
497    /// # extern crate futures;
498    /// use futures::executor::block_on;
499    /// use futures::future::*;
500    ///
501    /// # fn main() {
502    /// let x = 6;
503    /// let future = if x < 10 {
504    ///     ok::<_, bool>(x).left()
505    /// } else {
506    ///     empty().right()
507    /// };
508    ///
509    /// assert_eq!(x, block_on(future).unwrap());
510    /// # }
511    /// ```
512    #[deprecated(note = "use `left_future` instead")]
513    fn left<B>(self) -> Either<Self, B>
514        where B: Future<Item = Self::Item, Error = Self::Error>,
515              Self: Sized
516    {
517        Either::Left(self)
518    }
519
520    /// Wrap this future in an `Either` future, making it the left-hand variant
521    /// of that `Either`.
522    ///
523    /// This can be used in combination with the `right_future` method to write `if`
524    /// statements that evaluate to different futures in different branches.
525    ///
526    /// # Examples
527    ///
528    /// ```
529    /// # extern crate futures;
530    /// use futures::executor::block_on;
531    /// use futures::future::*;
532    ///
533    /// # fn main() {
534    /// let x = 6;
535    /// let future = if x < 10 {
536    ///     ok::<_, bool>(x).left_future()
537    /// } else {
538    ///     empty().right_future()
539    /// };
540    ///
541    /// assert_eq!(x, block_on(future).unwrap());
542    /// # }
543    /// ```
544    fn left_future<B>(self) -> Either<Self, B>
545        where B: Future<Item = Self::Item, Error = Self::Error>,
546              Self: Sized
547    {
548        Either::Left(self)
549    }
550
551    /// Wrap this future in an `Either` future, making it the right-hand variant
552    /// of that `Either`.
553    ///
554    /// This can be used in combination with the `left_future` method to write `if`
555    /// statements that evaluate to different futures in different branches.
556    ///
557    /// # Examples
558    ///
559    /// ```
560    /// # extern crate futures;
561    /// use futures::executor::block_on;
562    /// use futures::future::*;
563    ///
564    /// # fn main() {
565    /// let x = 6;
566    /// let future = if x < 10 {
567    ///     ok::<_, bool>(x).left()
568    /// } else {
569    ///     empty().right()
570    /// };
571    ///
572    /// assert_eq!(x, block_on(future).unwrap());
573    /// # }
574    /// ```
575    #[deprecated(note = "use `right_future` instead")]
576    fn right<A>(self) -> Either<A, Self>
577        where A: Future<Item = Self::Item, Error = Self::Error>,
578              Self: Sized,
579    {
580        Either::Right(self)
581    }
582
583    /// Wrap this future in an `Either` future, making it the right-hand variant
584    /// of that `Either`.
585    ///
586    /// This can be used in combination with the `left_future` method to write `if`
587    /// statements that evaluate to different futures in different branches.
588    ///
589    /// # Examples
590    ///
591    /// ```
592    /// # extern crate futures;
593    /// use futures::executor::block_on;
594    /// use futures::future::*;
595    ///
596    /// # fn main() {
597    /// let x = 6;
598    /// let future = if x < 10 {
599    ///     ok::<_, bool>(x).left_future()
600    /// } else {
601    ///     empty().right_future()
602    /// };
603    ///
604    /// assert_eq!(x, block_on(future).unwrap());
605    /// # }
606    /// ```
607    fn right_future<A>(self) -> Either<A, Self>
608        where A: Future<Item = Self::Item, Error = Self::Error>,
609              Self: Sized,
610    {
611        Either::Right(self)
612    }
613
614    /// Convert this future into a single element stream.
615    ///
616    /// The returned stream contains single success if this future resolves to
617    /// success or single error if this future resolves into error.
618    ///
619    /// # Examples
620    ///
621    /// ```
622    /// # extern crate futures;
623    /// # extern crate futures_executor;
624    /// use futures::prelude::*;
625    /// use futures::future;
626    /// use futures_executor::block_on;
627    ///
628    /// # fn main() {
629    /// let future = future::ok::<_, bool>(17);
630    /// let stream = future.into_stream();
631    /// let collected: Vec<_> = block_on(stream.collect()).unwrap();
632    /// assert_eq!(collected, vec![17]);
633    ///
634    /// let future = future::err::<bool, _>(19);
635    /// let stream = future.into_stream();
636    /// let collected: Result<Vec<_>, _> = block_on(stream.collect());
637    /// assert_eq!(collected, Err(19));
638    /// # }
639    /// ```
640    fn into_stream(self) -> IntoStream<Self>
641        where Self: Sized
642    {
643        into_stream::new(self)
644    }
645
646    /// Flatten the execution of this future when the successful result of this
647    /// future is itself another future.
648    ///
649    /// This can be useful when combining futures together to flatten the
650    /// computation out the final result. This method can only be called
651    /// when the successful result of this future itself implements the
652    /// `IntoFuture` trait and the error can be created from this future's error
653    /// type.
654    ///
655    /// This method is roughly equivalent to `self.and_then(|x| x)`.
656    ///
657    /// Note that this function consumes the receiving future and returns a
658    /// wrapped version of it.
659    ///
660    /// # Examples
661    ///
662    /// ```
663    /// # extern crate futures;
664    /// # extern crate futures_executor;
665    /// use futures::prelude::*;
666    /// use futures::future;
667    /// use futures_executor::block_on;
668    ///
669    /// # fn main() {
670    /// let nested_future = future::ok::<_, u32>(future::ok::<u32, u32>(1));
671    /// let future = nested_future.flatten();
672    /// assert_eq!(block_on(future), Ok(1));
673    /// # }
674    /// ```
675    ///
676    /// Calling `flatten` on an errored `Future`, or if the inner `Future` is
677    /// errored, will result in an errored `Future`:
678    ///
679    /// ```
680    /// # extern crate futures;
681    /// # extern crate futures_executor;
682    /// use futures::prelude::*;
683    /// use futures::future;
684    /// use futures_executor::block_on;
685    ///
686    /// # fn main() {
687    /// let nested_future = future::ok::<_, u32>(future::err::<u32, u32>(1));
688    /// let future = nested_future.flatten();
689    /// assert_eq!(block_on(future), Err(1));
690    /// # }
691    /// ```
692    fn flatten(self) -> Flatten<Self>
693        where Self::Item: IntoFuture<Error = <Self as Future>::Error>,
694        Self: Sized
695    {
696        let f = flatten::new(self);
697        assert_future::<<<Self as Future>::Item as IntoFuture>::Item,
698                        <<Self as Future>::Item as IntoFuture>::Error,
699                        _>(f)
700    }
701
702    /// Flatten the execution of this future when the successful result of this
703    /// future is a sink.
704    ///
705    /// This can be useful when sink initialization is deferred, and it is
706    /// convenient to work with that sink as if sink was available at the
707    /// call site.
708    ///
709    /// Note that this function consumes this future and returns a wrapped
710    /// version of it.
711    fn flatten_sink(self) -> FlattenSink<Self>
712        where <Self as Future>::Item: Sink<SinkError=Self::Error>,
713              Self: Sized
714    {
715        flatten_sink::new(self)
716    }
717
718    /// Flatten the execution of this future when the successful result of this
719    /// future is a stream.
720    ///
721    /// This can be useful when stream initialization is deferred, and it is
722    /// convenient to work with that stream as if stream was available at the
723    /// call site.
724    ///
725    /// Note that this function consumes this future and returns a wrapped
726    /// version of it.
727    ///
728    /// # Examples
729    ///
730    /// ```
731    /// # extern crate futures;
732    /// # extern crate futures_executor;
733    /// use futures::prelude::*;
734    /// use futures::future;
735    /// use futures::stream;
736    /// use futures_executor::block_on;
737    ///
738    /// # fn main() {
739    /// let stream_items = vec![17, 18, 19];
740    /// let future_of_a_stream = future::ok::<_, bool>(stream::iter_ok(stream_items));
741    ///
742    /// let stream = future_of_a_stream.flatten_stream();
743    /// let list: Vec<_> = block_on(stream.collect()).unwrap();
744    /// assert_eq!(list, vec![17, 18, 19]);
745    /// # }
746    /// ```
747    fn flatten_stream(self) -> FlattenStream<Self>
748        where <Self as Future>::Item: Stream<Error=Self::Error>,
749              Self: Sized
750    {
751        flatten_stream::new(self)
752    }
753
754    /// Fuse a future such that `poll` will never again be called once it has
755    /// completed.
756    ///
757    /// Currently once a future has returned `Ready` or `Err` from
758    /// `poll` any further calls could exhibit bad behavior such as blocking
759    /// forever, panicking, never returning, etc. If it is known that `poll`
760    /// may be called too often then this method can be used to ensure that it
761    /// has defined semantics.
762    ///
763    /// Once a future has been `fuse`d and it returns a completion from `poll`,
764    /// then it will forever return `Pending` from `poll` again (never
765    /// resolve).  This, unlike the trait's `poll` method, is guaranteed.
766    ///
767    /// This combinator will drop this future as soon as it's been completed to
768    /// ensure resources are reclaimed as soon as possible.
769    fn fuse(self) -> Fuse<Self>
770        where Self: Sized
771    {
772        let f = fuse::new(self);
773        assert_future::<Self::Item, Self::Error, _>(f)
774    }
775
776    /// Do something with the item of a future, passing it on.
777    ///
778    /// When using futures, you'll often chain several of them together.
779    /// While working on such code, you might want to check out what's happening at
780    /// various parts in the pipeline. To do that, insert a call to `inspect`.
781    ///
782    /// # Examples
783    ///
784    /// ```
785    /// # extern crate futures;
786    /// # extern crate futures_executor;
787    /// use futures::prelude::*;
788    /// use futures::future;
789    /// use futures_executor::block_on;
790    ///
791    /// # fn main() {
792    /// let future = future::ok::<u32, u32>(1);
793    /// let new_future = future.inspect(|&x| println!("about to resolve: {}", x));
794    /// assert_eq!(block_on(new_future), Ok(1));
795    /// # }
796    /// ```
797    fn inspect<F>(self, f: F) -> Inspect<Self, F>
798        where F: FnOnce(&Self::Item) -> (),
799              Self: Sized,
800    {
801        assert_future::<Self::Item, Self::Error, _>(inspect::new(self, f))
802    }
803
804    /// Do something with the error of a future, passing it on.
805    ///
806    /// When using futures, you'll often chain several of them together.
807    /// While working on such code, you might want to check out what's happening
808    /// to the errors at various parts in the pipeline. To do that, insert a
809    /// call to `inspect_err`.
810    ///
811    /// # Examples
812    ///
813    /// ```
814    /// # extern crate futures;
815    /// use futures::prelude::*;
816    /// use futures::future;
817    /// use futures::executor::block_on;
818    ///
819    /// # fn main() {
820    /// let future = future::err::<u32, u32>(1);
821    /// let new_future = future.inspect_err(|&x| println!("about to error: {}", x));
822    /// assert_eq!(block_on(new_future), Err(1));
823    /// # }
824    /// ```
825    fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
826        where F: FnOnce(&Self::Error) -> (),
827              Self: Sized,
828    {
829        assert_future::<Self::Item, Self::Error, _>(inspect_err::new(self, f))
830    }
831
832    /// Catches unwinding panics while polling the future.
833    ///
834    /// In general, panics within a future can propagate all the way out to the
835    /// task level. This combinator makes it possible to halt unwinding within
836    /// the future itself. It's most commonly used within task executors. It's
837    /// not recommended to use this for error handling.
838    ///
839    /// Note that this method requires the `UnwindSafe` bound from the standard
840    /// library. This isn't always applied automatically, and the standard
841    /// library provides an `AssertUnwindSafe` wrapper type to apply it
842    /// after-the fact. To assist using this method, the `Future` trait is also
843    /// implemented for `AssertUnwindSafe<F>` where `F` implements `Future`.
844    ///
845    /// This method is only available when the `std` feature of this
846    /// library is activated, and it is activated by default.
847    ///
848    /// # Examples
849    ///
850    /// ```rust
851    /// # extern crate futures;
852    /// # extern crate futures_executor;
853    /// use futures::prelude::*;
854    /// use futures::future::{self, FutureResult};
855    /// use futures_executor::block_on;
856    ///
857    /// # fn main() {
858    /// let mut future = future::ok::<i32, u32>(2);
859    /// assert!(block_on(future.catch_unwind()).is_ok());
860    ///
861    /// let mut future = future::lazy(|_| -> FutureResult<i32, u32> {
862    ///     panic!();
863    ///     future::ok::<i32, u32>(2)
864    /// });
865    /// assert!(block_on(future.catch_unwind()).is_err());
866    /// # }
867    /// ```
868    #[cfg(feature = "std")]
869    fn catch_unwind(self) -> CatchUnwind<Self>
870        where Self: Sized + ::std::panic::UnwindSafe
871    {
872        catch_unwind::new(self)
873    }
874
875    /// Create a cloneable handle to this future where all handles will resolve
876    /// to the same result.
877    ///
878    /// The shared() method provides a method to convert any future into a
879    /// cloneable future. It enables a future to be polled by multiple threads.
880    ///
881    /// The returned `Shared` future resolves successfully with
882    /// `SharedItem<Self::Item>` or erroneously with `SharedError<Self::Error>`.
883    /// Both `SharedItem` and `SharedError` implements `Deref` to allow shared
884    /// access to the underlying result. Ownership of `Self::Item` and
885    /// `Self::Error` cannot currently be reclaimed.
886    ///
887    /// This method is only available when the `std` feature of this
888    /// library is activated, and it is activated by default.
889    ///
890    /// # Examples
891    ///
892    /// ```
893    /// # extern crate futures;
894    /// # extern crate futures_executor;
895    /// use futures::prelude::*;
896    /// use futures::future;
897    /// use futures_executor::block_on;
898    ///
899    /// # fn main() {
900    /// let future = future::ok::<_, bool>(6);
901    /// let shared1 = future.shared();
902    /// let shared2 = shared1.clone();
903    ///
904    /// assert_eq!(6, *block_on(shared1).unwrap());
905    /// assert_eq!(6, *block_on(shared2).unwrap());
906    /// # }
907    /// ```
908    ///
909    /// ```
910    /// # extern crate futures;
911    /// # extern crate futures_executor;
912    /// use std::thread;
913    ///
914    /// use futures::prelude::*;
915    /// use futures::future;
916    /// use futures_executor::block_on;
917    ///
918    /// # fn main() {
919    /// let future = future::ok::<_, bool>(6);
920    /// let shared1 = future.shared();
921    /// let shared2 = shared1.clone();
922    /// let join_handle = thread::spawn(move || {
923    ///     assert_eq!(6, *block_on(shared2).unwrap());
924    /// });
925    /// assert_eq!(6, *block_on(shared1).unwrap());
926    /// join_handle.join().unwrap();
927    /// # }
928    /// ```
929    #[cfg(feature = "std")]
930    fn shared(self) -> Shared<Self>
931        where Self: Sized
932    {
933        shared::new(self)
934    }
935
936    /// Handle errors generated by this future by converting them into
937    /// `Self::Item`.
938    ///
939    /// Because it can never produce an error, the returned `Recover` future can
940    /// conform to any specific `Error` type, including `Never`.
941    ///
942    /// # Examples
943    ///
944    /// ```
945    /// # extern crate futures;
946    /// # extern crate futures_executor;
947    /// use futures::prelude::*;
948    /// use futures::future;
949    /// use futures_executor::block_on;
950    ///
951    /// # fn main() {
952    /// let future = future::err::<(), &str>("something went wrong");
953    /// let new_future = future.recover::<Never, _>(|_| ());
954    /// assert_eq!(block_on(new_future), Ok(()));
955    /// # }
956    /// ```
957    fn recover<E, F>(self, f: F) -> Recover<Self, E, F>
958        where Self: Sized,
959              F: FnOnce(Self::Error) -> Self::Item
960    {
961        recover::new(self, f)
962    }
963
964    /// Assigns the provided `Executor` to be used when spawning tasks
965    /// from within the future.
966    ///
967    /// # Examples
968    ///
969    /// ```
970    /// # extern crate futures;
971    /// # extern crate futures_executor;
972    /// use futures::prelude::*;
973    /// use futures::future;
974    /// use futures_executor::{block_on, spawn, ThreadPool};
975    ///
976    /// # fn main() {
977    /// let pool = ThreadPool::new().expect("unable to create threadpool");
978    /// let future = future::ok::<(), _>(());
979    /// let spawn_future = spawn(future).with_executor(pool);
980    /// assert_eq!(block_on(spawn_future), Ok(()));
981    /// # }
982    /// ```
983    #[cfg(feature = "std")]
984    fn with_executor<E>(self, executor: E) -> WithExecutor<Self, E>
985        where Self: Sized,
986              E: ::futures_core::executor::Executor
987    {
988        with_executor::new(self, executor)
989    }
990}
991
992// Just a helper function to ensure the futures we're returning all have the
993// right implementations.
994fn assert_future<A, B, F>(t: F) -> F
995    where F: Future<Item=A, Error=B>,
996{
997    t
998}