(Wangle) Then Magic
[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/FutureException.h>
27
28 namespace folly {
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 FutureException("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   template <bool isTry, typename R>
202   typename std::enable_if<isTry, R>::type get() {
203     return std::forward<R>(*this);
204   }
205
206   template <bool isTry, typename R>
207   typename std::enable_if<!isTry, R>::type get() {
208     return std::forward<R>(value());
209   }
210
211  private:
212   Contains contains_;
213   union {
214     T value_;
215     std::unique_ptr<exception_wrapper> e_;
216   };
217 };
218
219 /*
220  * Specialization of Try for void value type. Encapsulates either success or an
221  * exception.
222  */
223 template <>
224 class Try<void> {
225  public:
226   // Construct a Try holding a successful and void result
227   Try() : hasValue_(true) {}
228
229   /*
230    * Construct a Try with an exception_wrapper
231    *
232    * @param e The exception_wrapper
233    */
234   explicit Try(exception_wrapper e)
235     : hasValue_(false),
236       e_(folly::make_unique<exception_wrapper>(std::move(e))) {}
237
238   /*
239    * DEPRECATED
240    * Construct a Try with an exception_pointer
241    *
242    * @param ep The exception_pointer. Will be rethrown.
243    */
244   explicit Try(std::exception_ptr ep) DEPRECATED : hasValue_(false) {
245     try {
246       std::rethrow_exception(ep);
247     } catch (const std::exception& e) {
248       e_ = folly::make_unique<exception_wrapper>(std::current_exception(), e);
249     } catch (...) {
250       e_ = folly::make_unique<exception_wrapper>(std::current_exception());
251     }
252   }
253
254   // Copy assigner
255   Try& operator=(const Try<void>& t) {
256     hasValue_ = t.hasValue_;
257     if (t.e_) {
258       e_ = folly::make_unique<exception_wrapper>(*t.e_);
259     }
260     return *this;
261   }
262   // Copy constructor
263   Try(const Try<void>& t) {
264     *this = t;
265   }
266
267   // If the Try contains an exception, throws it
268   void value() const { throwIfFailed(); }
269   // Dereference operator. If the Try contains an exception, throws it
270   void operator*() const { return value(); }
271
272   // If the Try contains an exception, throws it
273   inline void throwIfFailed() const;
274
275   // @returns False if the Try contains an exception, true otherwise
276   bool hasValue() const { return hasValue_; }
277   // @returns True if the Try contains an exception, false otherwise
278   bool hasException() const { return !hasValue_; }
279
280   // @returns True if the Try contains an exception of type Ex, false otherwise
281   template <class Ex>
282   bool hasException() const {
283     return hasException() && e_->is_compatible_with<Ex>();
284   }
285
286   /*
287    * @throws FutureException if the Try doesn't contain an exception
288    *
289    * @returns mutable reference to the exception contained by this Try
290    */
291   exception_wrapper& exception() {
292     if (UNLIKELY(!hasException())) {
293       throw FutureException("exception(): Try does not contain an exception");
294     }
295     return *e_;
296   }
297
298   /*
299    * If the Try contains an exception and it is of type Ex, execute func(Ex)
300    *
301    * @param func a function that takes a single parameter of type const Ex&
302    *
303    * @returns True if the Try held an Ex and func was executed, false otherwise
304    */
305   template <class Ex, class F>
306   bool withException(F func) const {
307     if (!hasException()) {
308       return false;
309     }
310     return e_->with_exception<Ex>(std::move(func));
311   }
312
313   template <bool, typename R>
314   R get() {
315     return std::forward<R>(*this);
316   }
317
318  private:
319   bool hasValue_;
320   std::unique_ptr<exception_wrapper> e_{nullptr};
321 };
322
323 /*
324  * Extracts value from try and returns it. Throws if try contained an exception.
325  *
326  * @param t Try to extract value from
327  *
328  * @returns value contained in t
329  */
330 template <typename T>
331 T moveFromTry(Try<T>&& t);
332
333 /*
334  * Throws if try contained an exception.
335  *
336  * @param t Try to move from
337  */
338 void moveFromTry(Try<void>&& t);
339
340 /*
341  * @param f a function to execute and capture the result of (value or exception)
342  *
343  * @returns Try holding the result of f
344  */
345 template <typename F>
346 typename std::enable_if<
347   !std::is_same<typename std::result_of<F()>::type, void>::value,
348   Try<typename std::result_of<F()>::type>>::type
349 makeTryFunction(F&& f);
350
351 /*
352  * Specialization of makeTryFunction for void
353  *
354  * @param f a function to execute and capture the result of
355  *
356  * @returns Try<void> holding the result of f
357  */
358 template <typename F>
359 typename std::enable_if<
360   std::is_same<typename std::result_of<F()>::type, void>::value,
361   Try<void>>::type
362 makeTryFunction(F&& f);
363
364 } // folly
365
366 #include <folly/futures/Try-inl.h>