/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <algorithm> #include <exception> #include <functional> #include <memory> #include <type_traits> #include <utility> #include <vector> #include <folly/Optional.h> #include <folly/Portability.h> #include <folly/ScopeGuard.h> #include <folly/Try.h> #include <folly/Unit.h> #include <folly/Utility.h> #include <folly/executors/DrivableExecutor.h> #include <folly/executors/TimedDrivableExecutor.h> #include <folly/experimental/coro/Traits.h> #include <folly/fibers/Baton.h> #include <folly/functional/Invoke.h> #include <folly/futures/Portability.h> #include <folly/futures/Promise.h> #include <folly/futures/detail/Types.h> #include <folly/lang/Exception.h> // boring predeclarations and details #include <folly/futures/Future-pre.h> namespace folly { class FOLLY_EXPORT FutureException : public std::logic_error { … }; class FOLLY_EXPORT FutureInvalid : public FutureException { … }; /// At most one continuation may be attached to any given Future. /// /// If a continuation is attached to a future to which another continuation has /// already been attached, then an instance of FutureAlreadyContinued will be /// thrown instead. class FOLLY_EXPORT FutureAlreadyContinued : public FutureException { … }; class FOLLY_EXPORT FutureNotReady : public FutureException { … }; class FOLLY_EXPORT FutureCancellation : public FutureException { … }; class FOLLY_EXPORT FutureTimeout : public FutureException { … }; class FOLLY_EXPORT FuturePredicateDoesNotObtain : public FutureException { … }; class FOLLY_EXPORT FutureNoTimekeeper : public FutureException { … }; class FOLLY_EXPORT FutureNoExecutor : public FutureException { … }; template <class T> class Future; template <class T> class SemiFuture; template <class T> struct PromiseContract { … }; template <class T> struct SemiPromiseContract { … }; template <class T> class FutureSplitter; namespace futures { namespace detail { class FutureBaseHelper; template <class T> class FutureBase { … }; template <class T> Future<T> convertFuture(SemiFuture<T>&& sf, const Future<T>& f); class DeferredExecutor; template <typename T> DeferredExecutor* getDeferredExecutor(SemiFuture<T>& future); template <typename T> futures::detail::DeferredWrapper stealDeferredExecutor(SemiFuture<T>& future); } // namespace detail // Detach the SemiFuture by scheduling work onto exec. template <class T> void detachOn(folly::Executor::KeepAlive<> exec, folly::SemiFuture<T>&& fut); // Detach the SemiFuture by detaching work onto the global CPU executor. template <class T> void detachOnGlobalCPUExecutor(folly::SemiFuture<T>&& fut); // Detach the SemiFuture onto the global CPU executor after dur. // This will only hold a weak ref to the global executor and during // shutdown will cleanly drop the work. template <class T> void maybeDetachOnGlobalExecutorAfter( HighResDuration dur, folly::SemiFuture<T>&& fut); // Detach the SemiFuture with no executor. // NOTE: If there is deferred work of any sort on this SemiFuture // will leak and not be run. // Use at your own risk. template <class T> void detachWithoutExecutor(folly::SemiFuture<T>&& fut); } // namespace futures /// The interface (along with Future) for the consumer-side of a /// producer/consumer pair. /// /// Future vs. SemiFuture: /// /// - The consumer-side should generally start with a SemiFuture, not a Future. /// - Example, when a library creates and returns a future, it should usually /// return a `SemiFuture`, not a Future. /// - Reason: so the thread policy for continuations (`.thenValue`, etc.) can be /// specified by the library's caller (using `.via()`). /// - A SemiFuture is converted to a Future using `.via()`. /// - Use `makePromiseContract()` when creating both a Promise and an associated /// SemiFuture/Future. /// /// When practical, prefer SemiFuture/Future's nonblocking style/pattern: /// /// - the nonblocking style uses continuations, e.g., `.thenValue`, etc.; the /// continuations are deferred until the result is available. /// - the blocking style blocks until complete, e.g., `.wait()`, `.get()`, etc. /// - the two styles cannot be mixed within the same future; use one or the /// other. /// /// SemiFuture/Future also provide a back-channel so an interrupt can /// be sent from consumer to producer; see SemiFuture/Future's `raise()` /// and Promise's `setInterruptHandler()`. /// /// The consumer-side SemiFuture/Future objects should generally be accessed /// via a single thread. That thread is referred to as the 'consumer thread.' template <class T> class SemiFuture : private futures::detail::FutureBase<T> { … }; template <class T> SemiPromiseContract<T> makePromiseContract() { … } /// The interface (along with SemiFuture) for the consumer-side of a /// producer/consumer pair. /// /// Future vs. SemiFuture: /// /// - The consumer-side should generally start with a SemiFuture, not a Future. /// - Example, when a library creates and returns a future, it should usually /// return a `SemiFuture`, not a Future. /// - Reason: so the thread policy for continuations (`.thenValue`, etc.) can be /// specified by the library's caller (using `.via()`). /// - A SemiFuture is converted to a Future using `.via()`. /// - Use `makePromiseContract()` when creating both a Promise and an associated /// SemiFuture/Future. /// /// When practical, prefer SemiFuture/Future's nonblocking style/pattern: /// /// - the nonblocking style uses continuations, e.g., `.thenValue`, etc.; the /// continuations are deferred until the result is available. /// - the blocking style blocks until complete, e.g., `.wait()`, `.get()`, etc. /// - the two styles cannot be mixed within the same future; use one or the /// other. /// /// SemiFuture/Future also provide a back-channel so an interrupt can /// be sent from consumer to producer; see SemiFuture/Future's `raise()` /// and Promise's `setInterruptHandler()`. /// /// The consumer-side SemiFuture/Future objects should generally be accessed /// via a single thread. That thread is referred to as the 'consumer thread.' template <class T> class Future : private futures::detail::FutureBase<T> { … }; /// A Timekeeper handles the details of keeping time and fulfilling delay /// promises. The returned Future<Unit> will either complete after the /// elapsed time, or in the event of some kind of exceptional error may hold /// an exception. These Futures respond to cancellation. If you use a lot of /// Delays and many of them ultimately are unneeded (as would be the case for /// Delays that are used to trigger timeouts of async operations), then you /// can and should cancel them to reclaim resources. /// /// Users will typically get one of these via Future::sleep(HighResDuration dur) /// or use them implicitly behind the scenes by passing a timeout to some Future /// operation. /// /// Although we don't formally alias Delay = Future<Unit>, /// that's an appropriate term for it. People will probably also call these /// Timeouts, and that's ok I guess, but that term is so overloaded I thought /// it made sense to introduce a cleaner term. /// /// Remember that HighResDuration is a std::chrono duration (millisecond /// resolution at the time of writing). When writing code that uses specific /// durations, prefer using the explicit std::chrono type, e.g. /// std::chrono::milliseconds over HighResDuration. This makes the code more /// legible and means you won't be unpleasantly surprised if we redefine /// HighResDuration to microseconds, or something. /// /// timekeeper.after(std::chrono::duration_cast<HighResDuration>(someNanoseconds)) class Timekeeper { … }; template <class T> PromiseContract<T> makePromiseContract(Executor::KeepAlive<> e) { … } template <class F> auto makeAsyncTask(folly::Executor::KeepAlive<> ka, F&& func) { … } /// This namespace is for utility functions that would usually be static /// members of Future, except they don't make sense there because they don't /// depend on the template type (rather, on the type of their arguments in /// some cases). This is the least-bad naming scheme we could think of. Some /// of the functions herein have really-likely-to-collide names, like "map" /// and "sleep". namespace futures { /// Returns a Future that will complete after the specified duration. The /// HighResDuration typedef of a `std::chrono` duration type indicates the /// resolution you can expect to be meaningful (milliseconds at the time of /// writing). Normally you wouldn't need to specify a Timekeeper, we will /// use the global futures timekeeper (we run a thread whose job it is to /// keep time for futures timeouts) but we provide the option for power /// users. /// /// The Timekeeper thread will be lazily created the first time it is /// needed. If your program never uses any timeouts or other time-based /// Futures you will pay no Timekeeper thread overhead. SemiFuture<Unit> sleep(HighResDuration, Timekeeper* = nullptr); [[deprecated( "futures::sleep now returns a SemiFuture<Unit>. " "sleepUnsafe is deprecated. " "Please call futures::sleep and apply an executor with .via")]] Future<Unit> sleepUnsafe(HighResDuration, Timekeeper* = nullptr); /** * Set func as the callback for each input Future and return a vector of * Futures containing the results in the input order. */ template < class It, class F, class ItT = typename std::iterator_traits<It>::value_type, class Tag = std::enable_if_t<is_invocable_v<F, typename ItT::value_type&&>>, class Result = typename decltype(std::declval<ItT>().thenValue( std::declval<F>()))::value_type> std::vector<Future<Result>> mapValue(It first, It last, F func); /** * Set func as the callback for each input Future and return a vector of * Futures containing the results in the input order. */ template < class It, class F, class ItT = typename std::iterator_traits<It>::value_type, class Tag = std::enable_if_t<!is_invocable_v<F, typename ItT::value_type&&>>, class Result = typename decltype(std::declval<ItT>().thenTry( std::declval<F>()))::value_type> std::vector<Future<Result>> mapTry(It first, It last, F func, int = 0); /** * Set func as the callback for each input Future and return a vector of * Futures containing the results in the input order and completing on * exec. */ template < class It, class F, class ItT = typename std::iterator_traits<It>::value_type, class Tag = std::enable_if_t<is_invocable_v<F, typename ItT::value_type&&>>, class Result = typename decltype(std::move(std::declval<ItT>()) .via(std::declval<Executor*>()) .thenValue(std::declval<F>()))::value_type> std::vector<Future<Result>> mapValue(Executor& exec, It first, It last, F func); /** * Set func as the callback for each input Future and return a vector of * Futures containing the results in the input order and completing on * exec. */ template < class It, class F, class ItT = typename std::iterator_traits<It>::value_type, class Tag = std::enable_if_t<!is_invocable_v<F, typename ItT::value_type&&>>, class Result = typename decltype(std::move(std::declval<ItT>()) .via(std::declval<Executor*>()) .thenTry(std::declval<F>()))::value_type> std::vector<Future<Result>> mapTry( Executor& exec, It first, It last, F func, int = 0); // Sugar for the most common case template <class Collection, class F> auto mapValue(Collection&& c, F&& func) -> decltype(mapValue(c.begin(), c.end(), func)) { … } template <class Collection, class F> auto mapTry(Collection&& c, F&& func) -> decltype(mapTry(c.begin(), c.end(), func)) { … } // Sugar for the most common case template <class Collection, class F> auto mapValue(Executor& exec, Collection&& c, F&& func) -> decltype(mapValue(exec, c.begin(), c.end(), func)) { … } template <class Collection, class F> auto mapTry(Executor& exec, Collection&& c, F&& func) -> decltype(mapTry(exec, c.begin(), c.end(), func)) { … } /// Carry out the computation contained in the given future if /// the predicate holds. /// /// thunk behaves like std::function<Future<T2>(void)> or /// std::function<SemiFuture<T2>(void)> template <class F> auto when(bool p, F&& thunk) -> decltype(static_cast …); SemiFuture<Unit> wait(std::unique_ptr<fibers::Baton> baton); SemiFuture<Unit> wait(std::shared_ptr<fibers::Baton> baton); /** * Returns a lazy SemiFuture constructed by f, which also ensures that ensure is * called before completion. * f doesn't get called until the SemiFuture is activated (e.g. through a .get() * or .via() call). If f gets called, ensure is guaranteed to be called as well. */ template <typename F, class Ensure> auto ensure(F&& f, Ensure&& ensure); } // namespace futures /** Make a completed SemiFuture by moving in a value. e.g. string foo = "foo"; auto f = makeSemiFuture(std::move(foo)); or auto f = makeSemiFuture<string>("foo"); */ template <class T> SemiFuture<typename std::decay<T>::type> makeSemiFuture(T&& t); /** Make a completed void SemiFuture. */ SemiFuture<Unit> makeSemiFuture(); /** Make a SemiFuture by executing a function. If the function returns a value of type T, makeSemiFutureWith returns a completed SemiFuture<T>, capturing the value returned by the function. If the function returns a SemiFuture<T> already, makeSemiFutureWith returns just that. Either way, if the function throws, a failed Future is returned that captures the exception. */ // makeSemiFutureWith(SemiFuture<T>()) -> SemiFuture<T> template <class F> typename std::enable_if< isFutureOrSemiFuture<invoke_result_t<F>>::value, SemiFuture<typename invoke_result_t<F>::value_type>>::type makeSemiFutureWith(F&& func); // makeSemiFutureWith(T()) -> SemiFuture<T> // makeSemiFutureWith(void()) -> SemiFuture<Unit> template <class F> typename std::enable_if< !(isFutureOrSemiFuture<invoke_result_t<F>>::value), SemiFuture<lift_unit_t<invoke_result_t<F>>>>::type makeSemiFutureWith(F&& func); /// Make a failed Future from an exception_ptr. /// Because the Future's type cannot be inferred you have to specify it, e.g. /// /// auto f = makeSemiFuture<string>(std::current_exception()); template <class T> [[deprecated("use makeSemiFuture(exception_wrapper)")]] SemiFuture<T> makeSemiFuture(std::exception_ptr const& e); /// Make a failed SemiFuture from an exception_wrapper. template <class T> SemiFuture<T> makeSemiFuture(exception_wrapper ew); /** Make a SemiFuture from an exception type E that can be passed to std::make_exception_ptr(). */ template <class T, class E> typename std:: enable_if<std::is_base_of<std::exception, E>::value, SemiFuture<T>>::type makeSemiFuture(E const& e); /** Make a Future out of a Try */ template <class T> SemiFuture<T> makeSemiFuture(Try<T> t); /** Make a completed Future by moving in a value. e.g. string foo = "foo"; auto f = makeFuture(std::move(foo)); or auto f = makeFuture<string>("foo"); NOTE: This function is deprecated. Please use makeSemiFuture and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary. */ template <class T> Future<typename std::decay<T>::type> makeFuture(T&& t); /** Make a completed void Future. NOTE: This function is deprecated. Please use makeSemiFuture and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary. */ Future<Unit> makeFuture(); /** Make a Future by executing a function. If the function returns a value of type T, makeFutureWith returns a completed Future<T>, capturing the value returned by the function. If the function returns a Future<T> already, makeFutureWith returns just that. Either way, if the function throws, a failed Future is returned that captures the exception. Calling makeFutureWith(func) is equivalent to calling makeFuture().then(func). NOTE: This function is deprecated. Please use makeSemiFutureWith and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary. */ // makeFutureWith(Future<T>()) -> Future<T> template <class F> typename std:: enable_if<isFuture<invoke_result_t<F>>::value, invoke_result_t<F>>::type makeFutureWith(F&& func); // makeFutureWith(T()) -> Future<T> // makeFutureWith(void()) -> Future<Unit> template <class F> typename std::enable_if< !(isFuture<invoke_result_t<F>>::value), Future<lift_unit_t<invoke_result_t<F>>>>::type makeFutureWith(F&& func); /// Make a failed Future from an exception_ptr. /// Because the Future's type cannot be inferred you have to specify it, e.g. /// /// auto f = makeFuture<string>(std::current_exception()); template <class T> [[deprecated("use makeSemiFuture(exception_wrapper)")]] Future<T> makeFuture( std::exception_ptr const& e); /// Make a failed Future from an exception_wrapper. /// NOTE: This function is deprecated. Please use makeSemiFuture and pass the /// appropriate executor to .via on the returned SemiFuture to get a /// valid Future where necessary. template <class T> Future<T> makeFuture(exception_wrapper ew); /** Make a Future from an exception type E that can be passed to std::make_exception_ptr(). NOTE: This function is deprecated. Please use makeSemiFuture and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary. */ template <class T, class E> typename std::enable_if<std::is_base_of<std::exception, E>::value, Future<T>>:: type makeFuture(E const& e); /** Make a Future out of a Try NOTE: This function is deprecated. Please use makeSemiFuture and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary. */ template <class T> Future<T> makeFuture(Try<T> t); /* * Return a new Future that will call back on the given Executor. * This is just syntactic sugar for makeFuture().via(executor) * * @param executor the Executor to call back on * @param priority optionally, the priority to add with. Defaults to 0 which * represents medium priority. * * @returns a void Future that will call back on the given executor */ inline Future<Unit> via(Executor::KeepAlive<> executor); inline Future<Unit> via(Executor::KeepAlive<> executor, int8_t priority); /// Execute a function via the given executor and return a future. /// This is semantically equivalent to via(executor).then(func), but /// easier to read and slightly more efficient. template <class Func> auto via(Executor::KeepAlive<>, Func&& func) -> Future<typename isFutureOrSemiFuture< decltype(static_cast<Func&&>(func)())>::Inner>; /** When all the input Futures complete, the returned Future will complete. Errors do not cause early termination; this Future will always succeed after all its Futures have finished (whether successfully or with an error). The Futures are moved in, so your copies are invalid. If you need to chain further from these Futures, use the variant with an output iterator. This function is thread-safe for Futures running on different threads. But if you are doing anything non-trivial after, you will probably want to follow with `via(executor)` because it will complete in whichever thread the last Future completes in. The return type for Future<T> input is a SemiFuture<std::vector<Try<T>>> for collectX. collectXUnsafe returns an inline Future that erases the executor from the incoming Futures/SemiFutures. collectXUnsafe should be phased out and replaced with collectX(...).via(e) where e is a valid non-inline executor. */ // Unsafe variant, see above comment for details template <class InputIterator> Future<std::vector< Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>> collectAllUnsafe(InputIterator first, InputIterator last); // Unsafe variant sugar, see above comment for details template <class Collection> auto collectAllUnsafe(Collection&& c) -> decltype(collectAllUnsafe(c.begin(), c.end())) { … } template <class InputIterator> SemiFuture<std::vector< Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>> collectAll(InputIterator first, InputIterator last); template <class Collection> auto collectAll(Collection&& c) -> decltype(collectAll(c.begin(), c.end())) { … } // Unsafe variant of collectAll, see comment above for details. Returns // a Future<std::tuple<Try<T1>, Try<T2>, ...>> on the Inline executor. template <typename... Fs> Future<std::tuple<Try<typename remove_cvref_t<Fs>::value_type>...>> collectAllUnsafe(Fs&&... fs); /// This version takes a varying number of Futures instead of an iterator. /// The return type for (Future<T1>, Future<T2>, ...) input /// is a SemiFuture<std::tuple<Try<T1>, Try<T2>, ...>>. /// The Futures are moved in, so your copies are invalid. template <typename... Fs> SemiFuture<std::tuple<Try<typename remove_cvref_t<Fs>::value_type>...>> collectAll(Fs&&... fs); /// Like collectAll, but will short circuit on the first exception. Thus, the /// type of the returned SemiFuture is std::vector<T> instead of /// std::vector<Try<T>> template <class InputIterator> SemiFuture<std::vector< typename std::iterator_traits<InputIterator>::value_type::value_type>> collect(InputIterator first, InputIterator last); /// Sugar for the most common case template <class Collection> auto collect(Collection&& c) -> decltype(collect(c.begin(), c.end())) { … } // Unsafe variant of collect. Returns a Future<std::vector<T>> that // completes inline. template <class InputIterator> Future<std::vector< typename std::iterator_traits<InputIterator>::value_type::value_type>> collectUnsafe(InputIterator first, InputIterator last); /// Sugar for the most common unsafe case. Returns a Future<std::vector<T>> // that completes inline. template <class Collection> auto collectUnsafe(Collection&& c) -> decltype(collectUnsafe(c.begin(), c.end())) { … } /// Like collectAll, but will short circuit on the first exception. Thus, the /// type of the returned SemiFuture is std::tuple<T1, T2, ...> instead of /// std::tuple<Try<T1>, Try<T2>, ...> template <typename... Fs> SemiFuture<std::tuple<typename remove_cvref_t<Fs>::value_type...>> collect( Fs&&... fs); /** The result is a pair of the index of the first Future to complete and the Try. If multiple Futures complete at the same time (or are already complete when passed in), the "winner" is chosen non-deterministically. This function is thread-safe for Futures running on different threads. */ template <class InputIterator> SemiFuture<std::pair< size_t, Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>> collectAny(InputIterator first, InputIterator last); /// Sugar for the most common case template <class Collection> auto collectAny(Collection&& c) -> decltype(collectAny(c.begin(), c.end())) { … } /** Similar to collectAny, collectAnyWithoutException return the first Future to * complete without exceptions. If none of the future complete without * exceptions, the last exception will be returned as a result. */ template <class InputIterator> SemiFuture<std::pair< size_t, typename std::iterator_traits<InputIterator>::value_type::value_type>> collectAnyWithoutException(InputIterator first, InputIterator last); /// Sugar for the most common case template <class Collection> auto collectAnyWithoutException(Collection&& c) -> decltype(collectAnyWithoutException(c.begin(), c.end())) { … } /** when n Futures have completed, the Future completes with a vector of the index and Try of those n Futures (the indices refer to the original order, but the result vector will be in an arbitrary order) Not thread safe. */ template <class InputIterator> SemiFuture<std::vector<std::pair< size_t, Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>> collectN(InputIterator first, InputIterator last, size_t n); /// Sugar for the most common case template <class Collection> auto collectN(Collection&& c, size_t n) -> decltype(collectN(c.begin(), c.end(), n)) { … } /** window creates up to n Futures using the values in the collection, and then another Future for each Future that completes this is basically a sliding window of Futures of size n func must return a Future for each value in input */ template < class Collection, class F, class ItT = typename std::iterator_traits< typename Collection::iterator>::value_type, class Result = typename invoke_result_t<F, ItT&&>::value_type> std::vector<Future<Result>> window(Collection input, F func, size_t n); template < class Collection, class F, class ItT = typename std::iterator_traits< typename Collection::iterator>::value_type, class Result = typename invoke_result_t<F, ItT&&>::value_type> std::vector<Future<Result>> window( Executor::KeepAlive<> executor, Collection input, F func, size_t n); MaybeTryArg; /** repeatedly calls func on every result, e.g. reduce(reduce(reduce(T initial, result of first), result of second), ...) The type of the final result is a Future of the type of the initial value. Func can either return a T, or a Future<T> func is called in order of the input, see unorderedReduce if that is not a requirement */ template <class It, class T, class F> Future<T> reduce(It first, It last, T&& initial, F&& func); /// Sugar for the most common case template <class Collection, class T, class F> auto reduce(Collection&& c, T&& initial, F&& func) -> decltype(folly::reduce( c.begin(), c.end(), static_cast<T&&>(initial), static_cast<F&&>(func))) { … } /** like reduce, but calls func on finished futures as they complete does NOT keep the order of the input */ template <class It, class T, class F> Future<T> unorderedReduce(It first, It last, T initial, F func); /// Sugar for the most common case template <class Collection, class T, class F> auto unorderedReduce(Collection&& c, T&& initial, F&& func) -> decltype(folly::unorderedReduce( c.begin(), c.end(), static_cast<T&&>(initial), static_cast<F&&>(func))) { … } /// Carry out the computation contained in the given future if /// while the predicate continues to hold. /// /// if thunk behaves like std::function<Future<T2>(void)> /// returns Future<Unit> /// if thunk behaves like std::function<SemiFuture<T2>(void)> /// returns SemiFuture<Unit> /// predicate behaves like std::function<bool(void)> template <class P, class F> typename std::enable_if<isFuture<invoke_result_t<F>>::value, Future<Unit>>::type whileDo(P&& predicate, F&& thunk); template <class P, class F> typename std:: enable_if<isSemiFuture<invoke_result_t<F>>::value, SemiFuture<Unit>>::type whileDo(P&& predicate, F&& thunk); /// Repeat the given future (i.e., the computation it contains) n times. /// /// thunk behaves like /// std::function<Future<T2>(void)> /// or /// std::function<SemiFuture<T2>(void)> template <class F> auto times(int n, F&& thunk); } // namespace folly #if FOLLY_HAS_COROUTINES namespace folly { namespace detail { template <typename T> class FutureAwaiter { public: explicit FutureAwaiter(folly::Future<T>&& future) noexcept : future_(std::move(future)) {} bool await_ready() { if (future_.isReady()) { result_ = std::move(future_.result()); return true; } return false; } T await_resume() { return std::move(result_).value(); } Try<drop_unit_t<T>> await_resume_try() { return static_cast<Try<drop_unit_t<T>>>(std::move(result_)); } FOLLY_CORO_AWAIT_SUSPEND_NONTRIVIAL_ATTRIBUTES void await_suspend( coro::coroutine_handle<> h) { // FutureAwaiter may get destroyed as soon as the callback is executed. // Make sure the future object doesn't get destroyed until setCallback_ // returns. auto future = std::move(future_); future.setCallback_( [this, h](Executor::KeepAlive<>&&, Try<T>&& result) mutable { result_ = std::move(result); h.resume(); }); } private: folly::Future<T> future_; folly::Try<T> result_; }; } // namespace detail template <typename T> inline detail::FutureAwaiter<T> /* implicit */ operator co_await(Future<T>&& future) noexcept { return detail::FutureAwaiter<T>(std::move(future)); } } // namespace folly #endif #include <folly/futures/Future-inl.h>