4818e1ede2959a0010607adf3248370e59d67cb5
[folly.git] / folly / futures / Future.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <algorithm>
20 #include <exception>
21 #include <functional>
22 #include <memory>
23 #include <type_traits>
24 #include <vector>
25
26 #include <folly/Optional.h>
27 #include <folly/Portability.h>
28 #include <folly/ScopeGuard.h>
29 #include <folly/Try.h>
30 #include <folly/Utility.h>
31 #include <folly/executors/DrivableExecutor.h>
32 #include <folly/futures/FutureException.h>
33 #include <folly/futures/Promise.h>
34 #include <folly/futures/detail/Types.h>
35
36 // boring predeclarations and details
37 #include <folly/futures/Future-pre.h>
38
39 // not-boring helpers, e.g. all in folly::futures, makeFuture variants, etc.
40 // Needs to be included after Future-pre.h and before Future-inl.h
41 #include <folly/futures/helpers.h>
42
43 namespace folly {
44
45 template <class T>
46 class Future;
47
48 template <class T>
49 class SemiFuture;
50
51 namespace futures {
52 namespace detail {
53 template <class T>
54 class FutureBase {
55  public:
56   typedef T value_type;
57
58   /// Construct a Future from a value (perfect forwarding)
59   template <
60       class T2 = T,
61       typename = typename std::enable_if<
62           !isFuture<typename std::decay<T2>::type>::value &&
63           !isSemiFuture<typename std::decay<T2>::type>::value>::type>
64   /* implicit */ FutureBase(T2&& val);
65
66   template <class T2 = T>
67   /* implicit */ FutureBase(
68       typename std::enable_if<std::is_same<Unit, T2>::value>::type*);
69
70   template <
71       class... Args,
72       typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
73           type = 0>
74   explicit FutureBase(in_place_t, Args&&... args);
75
76   FutureBase(FutureBase<T> const&) = delete;
77   FutureBase(SemiFuture<T>&&) noexcept;
78   FutureBase(Future<T>&&) noexcept;
79
80   // not copyable
81   FutureBase(Future<T> const&) = delete;
82   FutureBase(SemiFuture<T> const&) = delete;
83
84   ~FutureBase();
85
86   /// Returns a reference to the result, with a reference category and const-
87   /// qualification equivalent to the reference category and const-qualification
88   /// of the receiver.
89   ///
90   /// If moved-from, throws NoState.
91   ///
92   /// If !isReady(), throws FutureNotReady.
93   ///
94   /// If an exception has been captured, throws that exception.
95   T& value() &;
96   T const& value() const&;
97   T&& value() &&;
98   T const&& value() const&&;
99
100   /** True when the result (or exception) is ready. */
101   bool isReady() const;
102
103   /// sugar for getTry().hasValue()
104   bool hasValue();
105
106   /// sugar for getTry().hasException()
107   bool hasException();
108
109   /// If the promise has been fulfilled, return an Optional with the Try<T>.
110   /// Otherwise return an empty Optional.
111   /// Note that this moves the Try<T> out.
112   Optional<Try<T>> poll();
113
114   /// This is not the method you're looking for.
115   ///
116   /// This needs to be public because it's used by make* and when*, and it's
117   /// not worth listing all those and their fancy template signatures as
118   /// friends. But it's not for public consumption.
119   template <class F>
120   void setCallback_(F&& func);
121
122   bool isActive() {
123     return core_->isActive();
124   }
125
126   template <class E>
127   void raise(E&& exception) {
128     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
129         std::forward<E>(exception)));
130   }
131
132   /// Raise an interrupt. If the promise holder has an interrupt
133   /// handler it will be called and potentially stop asynchronous work from
134   /// being done. This is advisory only - a promise holder may not set an
135   /// interrupt handler, or may do anything including ignore. But, if you know
136   /// your future supports this the most likely result is stopping or
137   /// preventing the asynchronous operation (if in time), and the promise
138   /// holder setting an exception on the future. (That may happen
139   /// asynchronously, of course.)
140   void raise(exception_wrapper interrupt);
141
142   void cancel() {
143     raise(FutureCancellation());
144   }
145
146  protected:
147   friend class Promise<T>;
148   template <class>
149   friend class SemiFuture;
150   template <class>
151   friend class Future;
152
153   using corePtr = futures::detail::Core<T>*;
154
155   // shared core state object
156   corePtr core_;
157
158   explicit FutureBase(corePtr obj) : core_(obj) {}
159
160   explicit FutureBase(futures::detail::EmptyConstruct) noexcept;
161
162   void detach();
163
164   void throwIfInvalid() const;
165
166   template <class FutureType>
167   void assign(FutureType&) noexcept;
168
169   Executor* getExecutor() {
170     return core_->getExecutor();
171   }
172
173   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
174     core_->setExecutor(x, priority);
175   }
176
177   // Variant: returns a value
178   // e.g. f.then([](Try<T> t){ return t.value(); });
179   template <typename F, typename R, bool isTry, typename... Args>
180   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
181   thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
182
183   // Variant: returns a Future
184   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
185   template <typename F, typename R, bool isTry, typename... Args>
186   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
187   thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
188 };
189 } // namespace detail
190 } // namespace futures
191
192 template <class T>
193 class SemiFuture : private futures::detail::FutureBase<T> {
194  private:
195   using Base = futures::detail::FutureBase<T>;
196   using DeferredExecutor = futures::detail::DeferredExecutor;
197
198  public:
199   static SemiFuture<T> makeEmpty(); // equivalent to moved-from
200
201   // Export public interface of FutureBase
202   // FutureBase is inherited privately to avoid subclasses being cast to
203   // a FutureBase pointer
204   using typename Base::value_type;
205
206   /// Construct a Future from a value (perfect forwarding)
207   template <
208       class T2 = T,
209       typename = typename std::enable_if<
210           !isFuture<typename std::decay<T2>::type>::value &&
211           !isSemiFuture<typename std::decay<T2>::type>::value>::type>
212   /* implicit */ SemiFuture(T2&& val) : Base(std::forward<T2>(val)) {}
213
214   template <class T2 = T>
215   /* implicit */ SemiFuture(
216       typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
217       : Base(p) {}
218
219   template <
220       class... Args,
221       typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
222           type = 0>
223   explicit SemiFuture(in_place_t, Args&&... args)
224       : Base(in_place, std::forward<Args>(args)...) {}
225
226   SemiFuture(SemiFuture<T> const&) = delete;
227   // movable
228   SemiFuture(SemiFuture<T>&&) noexcept;
229   // safe move-constructabilty from Future
230   /* implicit */ SemiFuture(Future<T>&&) noexcept;
231
232   using Base::cancel;
233   using Base::hasException;
234   using Base::hasValue;
235   using Base::isActive;
236   using Base::isReady;
237   using Base::poll;
238   using Base::raise;
239   using Base::setCallback_;
240   using Base::value;
241
242   SemiFuture& operator=(SemiFuture const&) = delete;
243   SemiFuture& operator=(SemiFuture&&) noexcept;
244   SemiFuture& operator=(Future<T>&&) noexcept;
245
246   /// Block until the future is fulfilled. Returns the value (moved out), or
247   /// throws the exception. The future must not already have a callback.
248   T get() &&;
249
250   /// Block until the future is fulfilled, or until timed out. Returns the
251   /// value (moved out), or throws the exception (which might be a TimedOut
252   /// exception).
253   T get(Duration dur) &&;
254
255   /// Block until the future is fulfilled, or until timed out. Returns the
256   /// Try of the value (moved out).
257   Try<T> getTry() &&;
258
259   /// Call e->drive() repeatedly until the future is fulfilled. Examples
260   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
261   /// value (moved out), or throws the exception.
262   T getVia(DrivableExecutor* e) &&;
263
264   /// Call e->drive() repeatedly until the future is fulfilled. Examples
265   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
266   /// Try of the value (moved out).
267   Try<T> getTryVia(DrivableExecutor* e) &&;
268
269   /// Block until this Future is complete. Returns a reference to this Future.
270   SemiFuture<T>& wait() &;
271
272   /// Overload of wait() for rvalue Futures
273   SemiFuture<T>&& wait() &&;
274
275   /// Block until this Future is complete or until the given Duration passes.
276   /// Returns a reference to this Future
277   SemiFuture<T>& wait(Duration) &;
278
279   /// Overload of wait(Duration) for rvalue Futures
280   SemiFuture<T>&& wait(Duration) &&;
281
282   /// Call e->drive() repeatedly until the future is fulfilled. Examples
283   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
284   /// reference to this SemiFuture so that you can chain calls if desired.
285   /// value (moved out), or throws the exception.
286   SemiFuture<T>& waitVia(DrivableExecutor* e) &;
287
288   /// Overload of waitVia() for rvalue Futures
289   SemiFuture<T>&& waitVia(DrivableExecutor* e) &&;
290
291   /// Returns an inactive Future which will call back on the other side of
292   /// executor (when it is activated).
293   ///
294   /// NB remember that Futures activate when they destruct. This is good,
295   /// it means that this will work:
296   ///
297   ///   f.via(e).then(a).then(b);
298   ///
299   /// a and b will execute in the same context (the far side of e), because
300   /// the Future (temporary variable) created by via(e) does not call back
301   /// until it destructs, which is after then(a) and then(b) have been wired
302   /// up.
303   ///
304   /// But this is still racy:
305   ///
306   ///   f = f.via(e).then(a);
307   ///   f.then(b);
308   // The ref-qualifier allows for `this` to be moved out so we
309   // don't get access-after-free situations in chaining.
310   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
311   inline Future<T> via(
312       Executor* executor,
313       int8_t priority = Executor::MID_PRI) &&;
314
315   /**
316    * Defer work to run on the consumer of the future.
317    * This work will be run eithe ron an executor that the caller sets on the
318    * SemiFuture, or inline with the call to .get().
319    * NB: This is a custom method because boost-blocking executors is a
320    * special-case for work deferral in folly. With more general boost-blocking
321    * support all executors would boost block and we would simply use some form
322    * of driveable executor here.
323    */
324   template <typename F>
325   SemiFuture<typename futures::detail::callableResult<T, F>::Return::value_type>
326   defer(F&& func) &&;
327
328   // Public as for setCallback_
329   // Ensure that a boostable executor performs work to chain deferred work
330   // cleanly
331   void boost_();
332
333  private:
334   friend class Promise<T>;
335   template <class>
336   friend class futures::detail::FutureBase;
337   template <class>
338   friend class SemiFuture;
339
340   using typename Base::corePtr;
341   using Base::setExecutor;
342   using Base::throwIfInvalid;
343
344   template <class T2>
345   friend SemiFuture<T2> makeSemiFuture(Try<T2>&&);
346
347   explicit SemiFuture(corePtr obj) : Base(obj) {}
348
349   explicit SemiFuture(futures::detail::EmptyConstruct) noexcept
350       : Base(futures::detail::EmptyConstruct{}) {}
351 };
352
353 template <class T>
354 class Future : private futures::detail::FutureBase<T> {
355  private:
356   using Base = futures::detail::FutureBase<T>;
357
358  public:
359   // Export public interface of FutureBase
360   // FutureBase is inherited privately to avoid subclasses being cast to
361   // a FutureBase pointer
362   using typename Base::value_type;
363
364   /// Construct a Future from a value (perfect forwarding)
365   template <
366       class T2 = T,
367       typename = typename std::enable_if<
368           !isFuture<typename std::decay<T2>::type>::value &&
369           !isSemiFuture<typename std::decay<T2>::type>::value>::type>
370   /* implicit */ Future(T2&& val) : Base(std::forward<T2>(val)) {}
371
372   template <class T2 = T>
373   /* implicit */ Future(
374       typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
375       : Base(p) {}
376
377   template <
378       class... Args,
379       typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
380           type = 0>
381   explicit Future(in_place_t, Args&&... args)
382       : Base(in_place, std::forward<Args>(args)...) {}
383
384   Future(Future<T> const&) = delete;
385   // movable
386   Future(Future<T>&&) noexcept;
387
388   // converting move
389   template <
390       class T2,
391       typename std::enable_if<
392           !std::is_same<T, typename std::decay<T2>::type>::value &&
393               std::is_constructible<T, T2&&>::value &&
394               std::is_convertible<T2&&, T>::value,
395           int>::type = 0>
396   /* implicit */ Future(Future<T2>&&);
397   template <
398       class T2,
399       typename std::enable_if<
400           !std::is_same<T, typename std::decay<T2>::type>::value &&
401               std::is_constructible<T, T2&&>::value &&
402               !std::is_convertible<T2&&, T>::value,
403           int>::type = 0>
404   explicit Future(Future<T2>&&);
405   template <
406       class T2,
407       typename std::enable_if<
408           !std::is_same<T, typename std::decay<T2>::type>::value &&
409               std::is_constructible<T, T2&&>::value,
410           int>::type = 0>
411   Future& operator=(Future<T2>&&);
412
413   using Base::cancel;
414   using Base::hasException;
415   using Base::hasValue;
416   using Base::isActive;
417   using Base::isReady;
418   using Base::poll;
419   using Base::raise;
420   using Base::setCallback_;
421   using Base::value;
422
423   static Future<T> makeEmpty(); // equivalent to moved-from
424
425   // not copyable
426   Future& operator=(Future const&) = delete;
427
428   // movable
429   Future& operator=(Future&&) noexcept;
430
431   /// Call e->drive() repeatedly until the future is fulfilled. Examples
432   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
433   /// value (moved out), or throws the exception.
434   T getVia(DrivableExecutor* e);
435
436   /// Call e->drive() repeatedly until the future is fulfilled. Examples
437   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
438   /// reference to the Try of the value.
439   Try<T>& getTryVia(DrivableExecutor* e);
440
441   /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
442   /// Future<T> instance.
443   template <class F = T>
444   typename std::
445       enable_if<isFuture<F>::value, Future<typename isFuture<T>::Inner>>::type
446       unwrap();
447
448   /// Returns an inactive Future which will call back on the other side of
449   /// executor (when it is activated).
450   ///
451   /// NB remember that Futures activate when they destruct. This is good,
452   /// it means that this will work:
453   ///
454   ///   f.via(e).then(a).then(b);
455   ///
456   /// a and b will execute in the same context (the far side of e), because
457   /// the Future (temporary variable) created by via(e) does not call back
458   /// until it destructs, which is after then(a) and then(b) have been wired
459   /// up.
460   ///
461   /// But this is still racy:
462   ///
463   ///   f = f.via(e).then(a);
464   ///   f.then(b);
465   // The ref-qualifier allows for `this` to be moved out so we
466   // don't get access-after-free situations in chaining.
467   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
468   inline Future<T> via(
469       Executor* executor,
470       int8_t priority = Executor::MID_PRI) &&;
471
472   /// This variant creates a new future, where the ref-qualifier && version
473   /// moves `this` out. This one is less efficient but avoids confusing users
474   /// when "return f.via(x);" fails.
475   inline Future<T> via(
476       Executor* executor,
477       int8_t priority = Executor::MID_PRI) &;
478
479   /** When this Future has completed, execute func which is a function that
480     takes one of:
481       (const) Try<T>&&
482       (const) Try<T>&
483       (const) Try<T>
484       (const) T&&
485       (const) T&
486       (const) T
487       (void)
488
489     Func shall return either another Future or a value.
490
491     A Future for the return type of func is returned.
492
493     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
494
495     The Future given to the functor is ready, and the functor may call
496     value(), which may rethrow if this has captured an exception. If func
497     throws, the exception will be captured in the Future that is returned.
498     */
499   template <typename F, typename R = futures::detail::callableResult<T, F>>
500   typename R::Return then(F&& func) {
501     return this->template thenImplementation<F, R>(
502         std::forward<F>(func), typename R::Arg());
503   }
504
505   /// Variant where func is an member function
506   ///
507   ///   struct Worker { R doWork(Try<T>); }
508   ///
509   ///   Worker *w;
510   ///   Future<R> f2 = f1.then(&Worker::doWork, w);
511   ///
512   /// This is just sugar for
513   ///
514   ///   f1.then(std::bind(&Worker::doWork, w));
515   template <typename R, typename Caller, typename... Args>
516   Future<typename isFuture<R>::Inner> then(
517       R (Caller::*func)(Args...),
518       Caller* instance);
519
520   /// Execute the callback via the given Executor. The executor doesn't stick.
521   ///
522   /// Contrast
523   ///
524   ///   f.via(x).then(b).then(c)
525   ///
526   /// with
527   ///
528   ///   f.then(x, b).then(c)
529   ///
530   /// In the former both b and c execute via x. In the latter, only b executes
531   /// via x, and c executes via the same executor (if any) that f had.
532   template <class Executor, class Arg, class... Args>
533   auto then(Executor* x, Arg&& arg, Args&&... args) {
534     auto oldX = this->getExecutor();
535     this->setExecutor(x);
536     return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
537         .via(oldX);
538   }
539
540   /// Convenience method for ignoring the value and creating a Future<Unit>.
541   /// Exceptions still propagate.
542   /// This function is identical to .unit().
543   Future<Unit> then();
544
545   /// Convenience method for ignoring the value and creating a Future<Unit>.
546   /// Exceptions still propagate.
547   /// This function is identical to parameterless .then().
548   Future<Unit> unit() {
549     return then();
550   }
551
552   /// Set an error callback for this Future. The callback should take a single
553   /// argument of the type that you want to catch, and should return a value of
554   /// the same type as this Future, or a Future of that type (see overload
555   /// below). For instance,
556   ///
557   /// makeFuture()
558   ///   .then([] {
559   ///     throw std::runtime_error("oh no!");
560   ///     return 42;
561   ///   })
562   ///   .onError([] (std::runtime_error& e) {
563   ///     LOG(INFO) << "std::runtime_error: " << e.what();
564   ///     return -1; // or makeFuture<int>(-1)
565   ///   });
566   template <class F>
567   typename std::enable_if<
568       !futures::detail::callableWith<F, exception_wrapper>::value &&
569           !futures::detail::callableWith<F, exception_wrapper&>::value &&
570           !futures::detail::Extract<F>::ReturnsFuture::value,
571       Future<T>>::type
572   onError(F&& func);
573
574   /// Overload of onError where the error callback returns a Future<T>
575   template <class F>
576   typename std::enable_if<
577       !futures::detail::callableWith<F, exception_wrapper>::value &&
578           !futures::detail::callableWith<F, exception_wrapper&>::value &&
579           futures::detail::Extract<F>::ReturnsFuture::value,
580       Future<T>>::type
581   onError(F&& func);
582
583   /// Overload of onError that takes exception_wrapper and returns Future<T>
584   template <class F>
585   typename std::enable_if<
586       futures::detail::callableWith<F, exception_wrapper>::value &&
587           futures::detail::Extract<F>::ReturnsFuture::value,
588       Future<T>>::type
589   onError(F&& func);
590
591   /// Overload of onError that takes exception_wrapper and returns T
592   template <class F>
593   typename std::enable_if<
594       futures::detail::callableWith<F, exception_wrapper>::value &&
595           !futures::detail::Extract<F>::ReturnsFuture::value,
596       Future<T>>::type
597   onError(F&& func);
598
599   /// func is like std::function<void()> and is executed unconditionally, and
600   /// the value/exception is passed through to the resulting Future.
601   /// func shouldn't throw, but if it does it will be captured and propagated,
602   /// and discard any value/exception that this Future has obtained.
603   template <class F>
604   Future<T> ensure(F&& func);
605
606   /// Like onError, but for timeouts. example:
607   ///
608   ///   Future<int> f = makeFuture<int>(42)
609   ///     .delayed(long_time)
610   ///     .onTimeout(short_time,
611   ///       []() -> int{ return -1; });
612   ///
613   /// or perhaps
614   ///
615   ///   Future<int> f = makeFuture<int>(42)
616   ///     .delayed(long_time)
617   ///     .onTimeout(short_time,
618   ///       []() { return makeFuture<int>(some_exception); });
619   template <class F>
620   Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
621
622   /// A Future's callback is executed when all three of these conditions have
623   /// become true: it has a value (set by the Promise), it has a callback (set
624   /// by then), and it is active (active by default).
625   ///
626   /// Inactive Futures will activate upon destruction.
627   FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
628     this->core_->activate();
629     return *this;
630   }
631   FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
632     this->core_->deactivate();
633     return *this;
634   }
635   FOLLY_DEPRECATED("do not use") Future<T> activate() && {
636     this->core_->activate();
637     return std::move(*this);
638   }
639   FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
640     this->core_->deactivate();
641     return std::move(*this);
642   }
643
644   /// Throw TimedOut if this Future does not complete within the given
645   /// duration from now. The optional Timeekeeper is as with futures::sleep().
646   Future<T> within(Duration, Timekeeper* = nullptr);
647
648   /// Throw the given exception if this Future does not complete within the
649   /// given duration from now. The optional Timeekeeper is as with
650   /// futures::sleep().
651   template <class E>
652   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
653
654   /// Delay the completion of this Future for at least this duration from
655   /// now. The optional Timekeeper is as with futures::sleep().
656   Future<T> delayed(Duration, Timekeeper* = nullptr);
657
658   /// Block until the future is fulfilled. Returns the value (moved out), or
659   /// throws the exception. The future must not already have a callback.
660   T get();
661
662   /// Block until the future is fulfilled, or until timed out. Returns the
663   /// value (moved out), or throws the exception (which might be a TimedOut
664   /// exception).
665   T get(Duration dur);
666
667   /** A reference to the Try of the value */
668   Try<T>& getTry();
669
670   /// Block until this Future is complete. Returns a reference to this Future.
671   Future<T>& wait() &;
672
673   /// Overload of wait() for rvalue Futures
674   Future<T>&& wait() &&;
675
676   /// Block until this Future is complete or until the given Duration passes.
677   /// Returns a reference to this Future
678   Future<T>& wait(Duration) &;
679
680   /// Overload of wait(Duration) for rvalue Futures
681   Future<T>&& wait(Duration) &&;
682
683   /// Call e->drive() repeatedly until the future is fulfilled. Examples
684   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
685   /// reference to this Future so that you can chain calls if desired.
686   /// value (moved out), or throws the exception.
687   Future<T>& waitVia(DrivableExecutor* e) &;
688
689   /// Overload of waitVia() for rvalue Futures
690   Future<T>&& waitVia(DrivableExecutor* e) &&;
691
692   /// If the value in this Future is equal to the given Future, when they have
693   /// both completed, the value of the resulting Future<bool> will be true. It
694   /// will be false otherwise (including when one or both Futures have an
695   /// exception)
696   Future<bool> willEqual(Future<T>&);
697
698   /// predicate behaves like std::function<bool(T const&)>
699   /// If the predicate does not obtain with the value, the result
700   /// is a folly::PredicateDoesNotObtain exception
701   template <class F>
702   Future<T> filter(F&& predicate);
703
704   /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
705   /// the result of collect or collectAll
706   template <class I, class F>
707   Future<I> reduce(I&& initial, F&& func);
708
709   /// Create a Future chain from a sequence of callbacks. i.e.
710   ///
711   ///   f.then(a).then(b).then(c)
712   ///
713   /// where f is a Future<A> and the result of the chain is a Future<D>
714   /// becomes
715   ///
716   ///   f.thenMulti(a, b, c);
717   template <class Callback, class... Callbacks>
718   auto thenMulti(Callback&& fn, Callbacks&&... fns) {
719     // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
720     return then(std::forward<Callback>(fn))
721         .thenMulti(std::forward<Callbacks>(fns)...);
722   }
723
724   template <class Callback>
725   auto thenMulti(Callback&& fn) {
726     // thenMulti with one callback is just a then
727     return then(std::forward<Callback>(fn));
728   }
729
730   /// Create a Future chain from a sequence of callbacks. i.e.
731   ///
732   ///   f.via(executor).then(a).then(b).then(c).via(oldExecutor)
733   ///
734   /// where f is a Future<A> and the result of the chain is a Future<D>
735   /// becomes
736   ///
737   ///   f.thenMultiWithExecutor(executor, a, b, c);
738   template <class Callback, class... Callbacks>
739   auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
740     // thenMultiExecutor with two callbacks is
741     // via(x).then(a).thenMulti(b, ...).via(oldX)
742     auto oldX = this->getExecutor();
743     this->setExecutor(x);
744     return then(std::forward<Callback>(fn))
745         .thenMulti(std::forward<Callbacks>(fns)...)
746         .via(oldX);
747   }
748
749   template <class Callback>
750   auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
751     // thenMulti with one callback is just a then with an executor
752     return then(x, std::forward<Callback>(fn));
753   }
754
755   // Convert this Future to a SemiFuture to safely export from a library
756   // without exposing a continuation interface
757   SemiFuture<T> semi() {
758     return SemiFuture<T>{std::move(*this)};
759   }
760
761  protected:
762   friend class Promise<T>;
763   template <class>
764   friend class futures::detail::FutureBase;
765   template <class>
766   friend class Future;
767   template <class>
768   friend class SemiFuture;
769
770   using Base::setExecutor;
771   using Base::throwIfInvalid;
772   using typename Base::corePtr;
773
774   explicit Future(corePtr obj) : Base(obj) {}
775
776   explicit Future(futures::detail::EmptyConstruct) noexcept
777       : Base(futures::detail::EmptyConstruct{}) {}
778
779   template <class T2>
780   friend Future<T2> makeFuture(Try<T2>&&);
781
782   /// Repeat the given future (i.e., the computation it contains)
783   /// n times.
784   ///
785   /// thunk behaves like std::function<Future<T2>(void)>
786   template <class F>
787   friend Future<Unit> times(int n, F&& thunk);
788
789   /// Carry out the computation contained in the given future if
790   /// the predicate holds.
791   ///
792   /// thunk behaves like std::function<Future<T2>(void)>
793   template <class F>
794   friend Future<Unit> when(bool p, F&& thunk);
795
796   /// Carry out the computation contained in the given future if
797   /// while the predicate continues to hold.
798   ///
799   /// thunk behaves like std::function<Future<T2>(void)>
800   ///
801   /// predicate behaves like std::function<bool(void)>
802   template <class P, class F>
803   friend Future<Unit> whileDo(P&& predicate, F&& thunk);
804 };
805
806 } // namespace folly
807
808 #include <folly/futures/Future-inl.h>