move wangle/futures to futures
[folly.git] / folly / futures / Try.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 <type_traits>
20 #include <exception>
21 #include <algorithm>
22 #include <folly/ExceptionWrapper.h>
23 #include <folly/Likely.h>
24 #include <folly/Memory.h>
25 #include <folly/futures/Deprecated.h>
26 #include <folly/futures/WangleException.h>
27
28 namespace folly { namespace wangle {
29
30 /*
31  * Try<T> is a wrapper that contains either an instance of T, an exception, or
32  * nothing. Its primary use case is as a representation of a Promise or Future's
33  * result and so it provides a number of methods that are useful in that
34  * context. Exceptions are stored as exception_wrappers so that the user can
35  * minimize rethrows if so desired.
36  *
37  * There is a specialization, Try<void>, which represents either success
38  * or an exception.
39  */
40 template <class T>
41 class Try {
42   static_assert(!std::is_reference<T>::value,
43                 "Try may not be used with reference types");
44
45   enum class Contains {
46     VALUE,
47     EXCEPTION,
48     NOTHING,
49   };
50
51  public:
52   /*
53    * The value type for the Try
54    */
55   typedef T element_type;
56
57   /*
58    * Construct an empty Try
59    */
60   Try() : contains_(Contains::NOTHING) {}
61
62   /*
63    * Construct a Try with a value by copy
64    *
65    * @param v The value to copy in
66    */
67   explicit Try(const T& v) : contains_(Contains::VALUE), value_(v) {}
68
69   /*
70    * Construct a Try with a value by move
71    *
72    * @param v The value to move in
73    */
74   explicit Try(T&& v) : contains_(Contains::VALUE), value_(std::move(v)) {}
75
76   /*
77    * Construct a Try with an exception_wrapper
78    *
79    * @param e The exception_wrapper
80    */
81   explicit Try(exception_wrapper e)
82     : contains_(Contains::EXCEPTION),
83       e_(folly::make_unique<exception_wrapper>(std::move(e))) {}
84
85   /*
86    * DEPRECATED
87    * Construct a Try with an exception_pointer
88    *
89    * @param ep The exception_pointer. Will be rethrown.
90    */
91   explicit Try(std::exception_ptr ep) DEPRECATED
92     : contains_(Contains::EXCEPTION) {
93     try {
94       std::rethrow_exception(ep);
95     } catch (const std::exception& e) {
96       e_ = folly::make_unique<exception_wrapper>(std::current_exception(), e);
97     } catch (...) {
98       e_ = folly::make_unique<exception_wrapper>(std::current_exception());
99     }
100   }
101
102   // Move constructor
103   Try(Try<T>&& t);
104   // Move assigner
105   Try& operator=(Try<T>&& t);
106
107   // Non-copyable
108   Try(const Try<T>& t) = delete;
109   // Non-copyable
110   Try& operator=(const Try<T>& t) = delete;
111
112   ~Try();
113
114   /*
115    * Get a mutable reference to the contained value. If the Try contains an
116    * exception it will be rethrown.
117    *
118    * @returns mutable reference to the contained value
119    */
120   T& value();
121   /*
122    * Get a const reference to the contained value. If the Try contains an
123    * exception it will be rethrown.
124    *
125    * @returns const reference to the contained value
126    */
127   const T& value() const;
128
129   /*
130    * If the Try contains an exception, rethrow it. Otherwise do nothing.
131    */
132   void throwIfFailed() const;
133
134   /*
135    * Const dereference operator. If the Try contains an exception it will be
136    * rethrown.
137    *
138    * @returns const reference to the contained value
139    */
140   const T& operator*() const { return value(); }
141   /*
142    * Dereference operator. If the Try contains an exception it will be rethrown.
143    *
144    * @returns mutable reference to the contained value
145    */
146   T& operator*() { return value(); }
147
148   /*
149    * Const arrow operator. If the Try contains an exception it will be
150    * rethrown.
151    *
152    * @returns const reference to the contained value
153    */
154   const T* operator->() const { return &value(); }
155   /*
156    * Arrow operator. If the Try contains an exception it will be rethrown.
157    *
158    * @returns mutable reference to the contained value
159    */
160   T* operator->() { return &value(); }
161
162   /*
163    * @returns True if the Try contains a value, false otherwise
164    */
165   bool hasValue() const { return contains_ == Contains::VALUE; }
166   /*
167    * @returns True if the Try contains an exception, false otherwise
168    */
169   bool hasException() const { return contains_ == Contains::EXCEPTION; }
170
171   /*
172    * @returns True if the Try contains an exception of type Ex, false otherwise
173    */
174   template <class Ex>
175   bool hasException() const {
176     return hasException() && e_->is_compatible_with<Ex>();
177   }
178
179   exception_wrapper& exception() {
180     if (UNLIKELY(!hasException())) {
181       throw WangleException("exception(): Try does not contain an exception");
182     }
183     return *e_;
184   }
185
186   /*
187    * If the Try contains an exception and it is of type Ex, execute func(Ex)
188    *
189    * @param func a function that takes a single parameter of type const Ex&
190    *
191    * @returns True if the Try held an Ex and func was executed, false otherwise
192    */
193   template <class Ex, class F>
194   bool withException(F func) const {
195     if (!hasException()) {
196       return false;
197     }
198     return e_->with_exception<Ex>(std::move(func));
199   }
200
201  private:
202   Contains contains_;
203   union {
204     T value_;
205     std::unique_ptr<exception_wrapper> e_;
206   };
207 };
208
209 /*
210  * Specialization of Try for void value type. Encapsulates either success or an
211  * exception.
212  */
213 template <>
214 class Try<void> {
215  public:
216   // Construct a Try holding a successful and void result
217   Try() : hasValue_(true) {}
218
219   /*
220    * Construct a Try with an exception_wrapper
221    *
222    * @param e The exception_wrapper
223    */
224   explicit Try(exception_wrapper e)
225     : hasValue_(false),
226       e_(folly::make_unique<exception_wrapper>(std::move(e))) {}
227
228   /*
229    * DEPRECATED
230    * Construct a Try with an exception_pointer
231    *
232    * @param ep The exception_pointer. Will be rethrown.
233    */
234   explicit Try(std::exception_ptr ep) DEPRECATED : hasValue_(false) {
235     try {
236       std::rethrow_exception(ep);
237     } catch (const std::exception& e) {
238       e_ = folly::make_unique<exception_wrapper>(std::current_exception(), e);
239     } catch (...) {
240       e_ = folly::make_unique<exception_wrapper>(std::current_exception());
241     }
242   }
243
244   // Copy assigner
245   Try& operator=(const Try<void>& t) {
246     hasValue_ = t.hasValue_;
247     if (t.e_) {
248       e_ = folly::make_unique<exception_wrapper>(*t.e_);
249     }
250     return *this;
251   }
252   // Copy constructor
253   Try(const Try<void>& t) {
254     *this = t;
255   }
256
257   // If the Try contains an exception, throws it
258   void value() const { throwIfFailed(); }
259   // Dereference operator. If the Try contains an exception, throws it
260   void operator*() const { return value(); }
261
262   // If the Try contains an exception, throws it
263   inline void throwIfFailed() const;
264
265   // @returns False if the Try contains an exception, true otherwise
266   bool hasValue() const { return hasValue_; }
267   // @returns True if the Try contains an exception, false otherwise
268   bool hasException() const { return !hasValue_; }
269
270   // @returns True if the Try contains an exception of type Ex, false otherwise
271   template <class Ex>
272   bool hasException() const {
273     return hasException() && e_->is_compatible_with<Ex>();
274   }
275
276   /*
277    * @throws WangleException if the Try doesn't contain an exception
278    *
279    * @returns mutable reference to the exception contained by this Try
280    */
281   exception_wrapper& exception() {
282     if (UNLIKELY(!hasException())) {
283       throw WangleException("exception(): Try does not contain an exception");
284     }
285     return *e_;
286   }
287
288   /*
289    * If the Try contains an exception and it is of type Ex, execute func(Ex)
290    *
291    * @param func a function that takes a single parameter of type const Ex&
292    *
293    * @returns True if the Try held an Ex and func was executed, false otherwise
294    */
295   template <class Ex, class F>
296   bool withException(F func) const {
297     if (!hasException()) {
298       return false;
299     }
300     return e_->with_exception<Ex>(std::move(func));
301   }
302
303  private:
304   bool hasValue_;
305   std::unique_ptr<exception_wrapper> e_{nullptr};
306 };
307
308 /*
309  * Extracts value from try and returns it. Throws if try contained an exception.
310  *
311  * @param t Try to extract value from
312  *
313  * @returns value contained in t
314  */
315 template <typename T>
316 T moveFromTry(wangle::Try<T>&& t);
317
318 /*
319  * Throws if try contained an exception.
320  *
321  * @param t Try to move from
322  */
323 void moveFromTry(wangle::Try<void>&& t);
324
325 /*
326  * @param f a function to execute and capture the result of (value or exception)
327  *
328  * @returns Try holding the result of f
329  */
330 template <typename F>
331 typename std::enable_if<
332   !std::is_same<typename std::result_of<F()>::type, void>::value,
333   Try<typename std::result_of<F()>::type>>::type
334 makeTryFunction(F&& f);
335
336 /*
337  * Specialization of makeTryFunction for void
338  *
339  * @param f a function to execute and capture the result of
340  *
341  * @returns Try<void> holding the result of f
342  */
343 template <typename F>
344 typename std::enable_if<
345   std::is_same<typename std::result_of<F()>::type, void>::value,
346   Try<void>>::type
347 makeTryFunction(F&& f);
348
349
350 }}
351
352 #include <folly/futures/Try-inl.h>