Fix #includes
[folly.git] / folly / wangle / Promise.h
1 /*
2  * Copyright 2014 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 <folly/wangle/Try.h>
20 #include <folly/wangle/Future.h>
21
22 namespace folly { namespace wangle {
23
24 // forward declaration
25 template <class T> class Future;
26
27 template <class T>
28 class Promise {
29 public:
30   Promise();
31   ~Promise();
32
33   // not copyable
34   Promise(Promise const&) = delete;
35   Promise& operator=(Promise const&) = delete;
36
37   // movable
38   Promise(Promise<T>&&);
39   Promise& operator=(Promise<T>&&);
40
41   /** Return a Future tied to the shared state. This can be called only
42     once, thereafter Future already retrieved exception will be raised. */
43   Future<T> getFuture();
44
45   /** Fulfil the Promise with an exception_ptr, e.g.
46     try {
47       ...
48     } catch (...) {
49       p.setException(std::current_exception());
50     }
51     */
52   void setException(std::exception_ptr const&);
53
54   /** Fulfil the Promise with an exception type E, which can be passed to
55     std::make_exception_ptr(). Useful for originating exceptions. If you
56     caught an exception the exception_ptr form is more appropriate.
57     */
58   template <class E> void setException(E const&);
59
60   /** Fulfil this Promise (only for Promise<void>) */
61   void setValue();
62
63   /** Set the value (use perfect forwarding for both move and copy) */
64   template <class M>
65   void setValue(M&& value);
66
67   void fulfilTry(Try<T>&& t);
68
69   /** Fulfil this Promise with the result of a function that takes no
70     arguments and returns something implicitly convertible to T.
71     Captures exceptions. e.g.
72
73     p.fulfil([] { do something that may throw; return a T; });
74   */
75   template <class F>
76   void fulfil(F&& func);
77
78 private:
79   typedef typename Future<T>::statePtr statePtr;
80
81   // Whether the Future has been retrieved (a one-time operation).
82   bool retrieved_;
83
84   // shared state object
85   statePtr state_;
86
87   void throwIfFulfilled();
88   void throwIfRetrieved();
89   void detach();
90 };
91
92 }}
93
94 #include <folly/wangle/Promise-inl.h>