2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include <folly/futures/Future.h>
22 /// This namespace is for utility functions that would usually be static
23 /// members of Future, except they don't make sense there because they don't
24 /// depend on the template type (rather, on the type of their arguments in
25 /// some cases). This is the least-bad naming scheme we could think of. Some
26 /// of the functions herein have really-likely-to-collide names, like "map"
29 /// Returns a Future that will complete after the specified duration. The
30 /// Duration typedef of a `std::chrono` duration type indicates the
31 /// resolution you can expect to be meaningful (milliseconds at the time of
32 /// writing). Normally you wouldn't need to specify a Timekeeper, we will
33 /// use the global futures timekeeper (we run a thread whose job it is to
34 /// keep time for futures timeouts) but we provide the option for power
37 /// The Timekeeper thread will be lazily created the first time it is
38 /// needed. If your program never uses any timeouts or other time-based
39 /// Futures you will pay no Timekeeper thread overhead.
40 Future<void> sleep(Duration, Timekeeper* = nullptr);
43 * Set func as the callback for each input Future and return a vector of
44 * Futures containing the results in the input order.
46 template <class It, class F,
47 class ItT = typename std::iterator_traits<It>::value_type,
49 = typename decltype(std::declval<ItT>().then(std::declval<F>()))::value_type>
50 std::vector<Future<Result>> map(It first, It last, F func);
52 // Sugar for the most common case
53 template <class Collection, class F>
54 auto map(Collection&& c, F&& func)
55 -> decltype(map(c.begin(), c.end(), func)) {
56 return map(c.begin(), c.end(), std::forward<F>(func));
62 Make a completed Future by moving in a value. e.g.
65 auto f = makeFuture(std::move(foo));
69 auto f = makeFuture<string>("foo");
72 Future<typename std::decay<T>::type> makeFuture(T&& t);
74 /** Make a completed void Future. */
75 Future<void> makeFuture();
77 /** Make a completed Future by executing a function. If the function throws
78 we capture the exception, otherwise we capture the result. */
82 typename std::enable_if<
83 !std::is_reference<F>::value, bool>::type sdf = false)
84 -> Future<decltype(func())>;
89 -> Future<decltype(func())>;
91 /// Make a failed Future from an exception_ptr.
92 /// Because the Future's type cannot be inferred you have to specify it, e.g.
94 /// auto f = makeFuture<string>(std::current_exception());
96 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
98 /// Make a failed Future from an exception_wrapper.
100 Future<T> makeFuture(exception_wrapper ew);
102 /** Make a Future from an exception type E that can be passed to
103 std::make_exception_ptr(). */
104 template <class T, class E>
105 typename std::enable_if<std::is_base_of<std::exception, E>::value,
107 makeFuture(E const& e);
109 /** Make a Future out of a Try */
111 Future<T> makeFuture(Try<T>&& t);
114 * Return a new Future that will call back on the given Executor.
115 * This is just syntactic sugar for makeFuture().via(executor)
117 * @param executor the Executor to call back on
118 * @param priority optionally, the priority to add with. Defaults to 0 which
119 * represents medium priority.
121 * @returns a void Future that will call back on the given executor
123 inline Future<void> via(
125 int8_t priority = Executor::MID_PRI);
127 /** When all the input Futures complete, the returned Future will complete.
128 Errors do not cause early termination; this Future will always succeed
129 after all its Futures have finished (whether successfully or with an
132 The Futures are moved in, so your copies are invalid. If you need to
133 chain further from these Futures, use the variant with an output iterator.
135 This function is thread-safe for Futures running on different threads. But
136 if you are doing anything non-trivial after, you will probably want to
137 follow with `via(executor)` because it will complete in whichever thread the
138 last Future completes in.
140 The return type for Future<T> input is a Future<std::vector<Try<T>>>
142 template <class InputIterator>
143 Future<std::vector<Try<
144 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
145 collectAll(InputIterator first, InputIterator last);
147 /// Sugar for the most common case
148 template <class Collection>
149 auto collectAll(Collection&& c) -> decltype(collectAll(c.begin(), c.end())) {
150 return collectAll(c.begin(), c.end());
153 /// This version takes a varying number of Futures instead of an iterator.
154 /// The return type for (Future<T1>, Future<T2>, ...) input
155 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
156 /// The Futures are moved in, so your copies are invalid.
157 template <typename... Fs>
158 typename detail::CollectAllVariadicContext<
159 typename std::decay<Fs>::type::value_type...>::type
160 collectAll(Fs&&... fs);
162 /// Like collectAll, but will short circuit on the first exception. Thus, the
163 /// type of the returned Future is std::vector<T> instead of
164 /// std::vector<Try<T>>
165 template <class InputIterator>
166 Future<typename detail::CollectContext<
167 typename std::iterator_traits<InputIterator>::value_type::value_type
169 collect(InputIterator first, InputIterator last);
171 /// Sugar for the most common case
172 template <class Collection>
173 auto collect(Collection&& c) -> decltype(collect(c.begin(), c.end())) {
174 return collect(c.begin(), c.end());
177 /// Like collectAll, but will short circuit on the first exception. Thus, the
178 /// type of the returned Future is std::tuple<T1, T2, ...> instead of
179 /// std::tuple<Try<T1>, Try<T2>, ...>
180 template <typename... Fs>
181 typename detail::CollectVariadicContext<
182 typename std::decay<Fs>::type::value_type...>::type
185 /** The result is a pair of the index of the first Future to complete and
186 the Try. If multiple Futures complete at the same time (or are already
187 complete when passed in), the "winner" is chosen non-deterministically.
189 This function is thread-safe for Futures running on different threads.
191 template <class InputIterator>
194 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
195 collectAny(InputIterator first, InputIterator last);
197 /// Sugar for the most common case
198 template <class Collection>
199 auto collectAny(Collection&& c) -> decltype(collectAny(c.begin(), c.end())) {
200 return collectAny(c.begin(), c.end());
203 /** when n Futures have completed, the Future completes with a vector of
204 the index and Try of those n Futures (the indices refer to the original
205 order, but the result vector will be in an arbitrary order)
209 template <class InputIterator>
210 Future<std::vector<std::pair<
212 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
213 collectN(InputIterator first, InputIterator last, size_t n);
215 /// Sugar for the most common case
216 template <class Collection>
217 auto collectN(Collection&& c, size_t n)
218 -> decltype(collectN(c.begin(), c.end(), n)) {
219 return collectN(c.begin(), c.end(), n);
222 /** window creates up to n Futures using the values
223 in the collection, and then another Future for each Future
226 this is basically a sliding window of Futures of size n
228 func must return a Future for each value in input
230 template <class Collection, class F,
231 class ItT = typename std::iterator_traits<
232 typename Collection::iterator>::value_type,
233 class Result = typename detail::resultOf<F, ItT&&>::value_type>
234 std::vector<Future<Result>>
235 window(Collection input, F func, size_t n);
237 template <typename F, typename T, typename ItT>
238 using MaybeTryArg = typename std::conditional<
239 detail::callableWith<F, T&&, Try<ItT>&&>::value, Try<ItT>, ItT>::type;
241 template<typename F, typename T, typename Arg>
242 using isFutureResult = isFuture<typename std::result_of<F(T&&, Arg&&)>::type>;
244 /** repeatedly calls func on every result, e.g.
245 reduce(reduce(reduce(T initial, result of first), result of second), ...)
247 The type of the final result is a Future of the type of the initial value.
249 Func can either return a T, or a Future<T>
251 func is called in order of the input, see unorderedReduce if that is not
254 template <class It, class T, class F>
255 Future<T> reduce(It first, It last, T&& initial, F&& func);
257 /// Sugar for the most common case
258 template <class Collection, class T, class F>
259 auto reduce(Collection&& c, T&& initial, F&& func)
260 -> decltype(reduce(c.begin(), c.end(), std::forward<T>(initial),
261 std::forward<F>(func))) {
265 std::forward<T>(initial),
266 std::forward<F>(func));
269 /** like reduce, but calls func on finished futures as they complete
270 does NOT keep the order of the input
272 template <class It, class T, class F,
273 class ItT = typename std::iterator_traits<It>::value_type::value_type,
274 class Arg = MaybeTryArg<F, T, ItT>>
275 Future<T> unorderedReduce(It first, It last, T initial, F func);
277 /// Sugar for the most common case
278 template <class Collection, class T, class F>
279 auto unorderedReduce(Collection&& c, T&& initial, F&& func)
280 -> decltype(unorderedReduce(c.begin(), c.end(), std::forward<T>(initial),
281 std::forward<F>(func))) {
282 return unorderedReduce(
285 std::forward<T>(initial),
286 std::forward<F>(func));