Log (de)compression bytes
[folly.git] / folly / executors / FutureExecutor.h
1 /*
2  * Copyright 2017-present 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 #include <folly/futures/Future.h>
19
20 namespace folly {
21
22 template <typename ExecutorImpl>
23 class FutureExecutor : public ExecutorImpl {
24  public:
25   template <typename... Args>
26   explicit FutureExecutor(Args&&... args)
27       : ExecutorImpl(std::forward<Args>(args)...) {}
28
29   /*
30    * Given a function func that returns a Future<T>, adds that function to the
31    * contained Executor and returns a Future<T> which will be fulfilled with
32    * func's result once it has been executed.
33    *
34    * For example: auto f = futureExecutor.addFuture([](){
35    *                return doAsyncWorkAndReturnAFuture();
36    *              });
37    */
38   template <typename F>
39   typename std::enable_if<
40       folly::isFuture<typename std::result_of<F()>::type>::value,
41       typename std::result_of<F()>::type>::type
42   addFuture(F func) {
43     typedef typename std::result_of<F()>::type::value_type T;
44     folly::Promise<T> promise;
45     auto future = promise.getFuture();
46     ExecutorImpl::add(
47         [ promise = std::move(promise), func = std::move(func) ]() mutable {
48           func().then([promise = std::move(promise)](
49               folly::Try<T> && t) mutable { promise.setTry(std::move(t)); });
50         });
51     return future;
52   }
53
54   /*
55    * Similar to addFuture above, but takes a func that returns some non-Future
56    * type T.
57    *
58    * For example: auto f = futureExecutor.addFuture([]() {
59    *                return 42;
60    *              });
61    */
62   template <typename F>
63   typename std::enable_if<
64       !folly::isFuture<typename std::result_of<F()>::type>::value,
65       folly::Future<typename folly::Unit::Lift<
66           typename std::result_of<F()>::type>::type>>::type
67   addFuture(F func) {
68     using T =
69         typename folly::Unit::Lift<typename std::result_of<F()>::type>::type;
70     folly::Promise<T> promise;
71     auto future = promise.getFuture();
72     ExecutorImpl::add(
73         [ promise = std::move(promise), func = std::move(func) ]() mutable {
74           promise.setWith(std::move(func));
75         });
76     return future;
77   }
78 };
79
80 } // namespace folly