support using co_await with folly::Optional when it is available
[folly.git] / folly / Optional.h
1 /*
2  * Copyright 2017 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 /*
20  * Optional - For conditional initialization of values, like boost::optional,
21  * but with support for move semantics and emplacement.  Reference type support
22  * has not been included due to limited use cases and potential confusion with
23  * semantics of assignment: Assigning to an optional reference could quite
24  * reasonably copy its value or redirect the reference.
25  *
26  * Optional can be useful when a variable might or might not be needed:
27  *
28  *  Optional<Logger> maybeLogger = ...;
29  *  if (maybeLogger) {
30  *    maybeLogger->log("hello");
31  *  }
32  *
33  * Optional enables a 'null' value for types which do not otherwise have
34  * nullability, especially useful for parameter passing:
35  *
36  * void testIterator(const unique_ptr<Iterator>& it,
37  *                   initializer_list<int> idsExpected,
38  *                   Optional<initializer_list<int>> ranksExpected = none) {
39  *   for (int i = 0; it->next(); ++i) {
40  *     EXPECT_EQ(it->doc().id(), idsExpected[i]);
41  *     if (ranksExpected) {
42  *       EXPECT_EQ(it->doc().rank(), (*ranksExpected)[i]);
43  *     }
44  *   }
45  * }
46  *
47  * Optional models OptionalPointee, so calling 'get_pointer(opt)' will return a
48  * pointer to nullptr if the 'opt' is empty, and a pointer to the value if it is
49  * not:
50  *
51  *  Optional<int> maybeInt = ...;
52  *  if (int* v = get_pointer(maybeInt)) {
53  *    cout << *v << endl;
54  *  }
55  */
56
57 #include <cstddef>
58 #include <functional>
59 #include <new>
60 #include <stdexcept>
61 #include <type_traits>
62 #include <utility>
63
64 #include <folly/Launder.h>
65 #include <folly/Portability.h>
66 #include <folly/Utility.h>
67
68 namespace folly {
69
70 template <class Value>
71 class Optional;
72
73 namespace detail {
74 struct NoneHelper {};
75
76 // Allow each translation unit to control its own -fexceptions setting.
77 // If exceptions are disabled, std::terminate() will be called instead of
78 // throwing OptionalEmptyException when the condition fails.
79 [[noreturn]] void throw_optional_empty_exception();
80
81 template <class Value>
82 struct OptionalPromiseReturn;
83 } // namespace detail
84
85 typedef int detail::NoneHelper::*None;
86
87 const None none = nullptr;
88
89 class OptionalEmptyException : public std::runtime_error {
90  public:
91   OptionalEmptyException()
92       : std::runtime_error("Empty Optional cannot be unwrapped") {}
93 };
94
95 template <class Value>
96 class Optional {
97  public:
98   typedef Value value_type;
99
100   static_assert(
101       !std::is_reference<Value>::value,
102       "Optional may not be used with reference types");
103   static_assert(
104       !std::is_abstract<Value>::value,
105       "Optional may not be used with abstract types");
106
107   Optional() noexcept {}
108
109   Optional(const Optional& src) noexcept(
110       std::is_nothrow_copy_constructible<Value>::value) {
111     if (src.hasValue()) {
112       storage_.construct(src.value());
113     }
114   }
115
116   Optional(Optional&& src) noexcept(
117       std::is_nothrow_move_constructible<Value>::value) {
118     if (src.hasValue()) {
119       storage_.construct(std::move(src.value()));
120       src.clear();
121     }
122   }
123
124   /* implicit */ Optional(const None&) noexcept {}
125
126   /* implicit */ Optional(Value&& newValue) noexcept(
127       std::is_nothrow_move_constructible<Value>::value) {
128     storage_.construct(std::move(newValue));
129   }
130
131   /* implicit */ Optional(const Value& newValue) noexcept(
132       std::is_nothrow_copy_constructible<Value>::value) {
133     storage_.construct(newValue);
134   }
135
136   template <typename... Args>
137   explicit Optional(in_place_t, Args&&... args) noexcept(
138       std::is_nothrow_constructible<Value, Args...>::value) {
139     storage_.construct(std::forward<Args>(args)...);
140   }
141
142   // Used only when an Optional is used with coroutines on MSVC
143   /* implicit */ Optional(const detail::OptionalPromiseReturn<Value>& p)
144       : Optional{} {
145     p.promise_->value_ = this;
146   }
147
148   void assign(const None&) {
149     clear();
150   }
151
152   void assign(Optional&& src) {
153     if (this != &src) {
154       if (src.hasValue()) {
155         assign(std::move(src.value()));
156         src.clear();
157       } else {
158         clear();
159       }
160     }
161   }
162
163   void assign(const Optional& src) {
164     if (src.hasValue()) {
165       assign(src.value());
166     } else {
167       clear();
168     }
169   }
170
171   void assign(Value&& newValue) {
172     if (hasValue()) {
173       *storage_.value_pointer() = std::move(newValue);
174     } else {
175       storage_.construct(std::move(newValue));
176     }
177   }
178
179   void assign(const Value& newValue) {
180     if (hasValue()) {
181       *storage_.value_pointer() = newValue;
182     } else {
183       storage_.construct(newValue);
184     }
185   }
186
187   template <class Arg>
188   Optional& operator=(Arg&& arg) {
189     assign(std::forward<Arg>(arg));
190     return *this;
191   }
192
193   Optional& operator=(Optional&& other) noexcept(
194       std::is_nothrow_move_assignable<Value>::value) {
195     assign(std::move(other));
196     return *this;
197   }
198
199   Optional& operator=(const Optional& other) noexcept(
200       std::is_nothrow_copy_assignable<Value>::value) {
201     assign(other);
202     return *this;
203   }
204
205   template <class... Args>
206   void emplace(Args&&... args) {
207     clear();
208     storage_.construct(std::forward<Args>(args)...);
209   }
210
211   void clear() {
212     storage_.clear();
213   }
214
215   const Value& value() const & {
216     require_value();
217     return *storage_.value_pointer();
218   }
219
220   Value& value() & {
221     require_value();
222     return *storage_.value_pointer();
223   }
224
225   Value&& value() && {
226     require_value();
227     return std::move(*storage_.value_pointer());
228   }
229
230   const Value&& value() const && {
231     require_value();
232     return std::move(*storage_.value_pointer());
233   }
234
235   const Value* get_pointer() const & {
236     return storage_.value_pointer();
237   }
238   Value* get_pointer() & {
239     return storage_.value_pointer();
240   }
241   Value* get_pointer() && = delete;
242
243   bool hasValue() const noexcept {
244     return storage_.hasValue();
245   }
246
247   explicit operator bool() const noexcept {
248     return hasValue();
249   }
250
251   const Value& operator*() const & {
252     return value();
253   }
254   Value& operator*() & {
255     return value();
256   }
257   const Value&& operator*() const && {
258     return std::move(value());
259   }
260   Value&& operator*() && {
261     return std::move(value());
262   }
263
264   const Value* operator->() const {
265     return &value();
266   }
267   Value* operator->() {
268     return &value();
269   }
270
271   // Return a copy of the value if set, or a given default if not.
272   template <class U>
273   Value value_or(U&& dflt) const & {
274     if (storage_.hasValue()) {
275       return *storage_.value_pointer();
276     }
277
278     return std::forward<U>(dflt);
279   }
280
281   template <class U>
282   Value value_or(U&& dflt) && {
283     if (storage_.hasValue()) {
284       return std::move(*storage_.value_pointer());
285     }
286
287     return std::forward<U>(dflt);
288   }
289
290  private:
291   void require_value() const {
292     if (!storage_.hasValue()) {
293       detail::throw_optional_empty_exception();
294     }
295   }
296
297   struct StorageTriviallyDestructible {
298    protected:
299     bool hasValue_;
300     typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
301         value_[1];
302
303    public:
304     StorageTriviallyDestructible() : hasValue_{false} {}
305     void clear() {
306       hasValue_ = false;
307     }
308   };
309
310   struct StorageNonTriviallyDestructible {
311    protected:
312     bool hasValue_;
313     typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
314         value_[1];
315
316    public:
317     StorageNonTriviallyDestructible() : hasValue_{false} {}
318     ~StorageNonTriviallyDestructible() {
319       clear();
320     }
321
322     void clear() {
323       if (hasValue_) {
324         hasValue_ = false;
325         launder(reinterpret_cast<Value*>(value_))->~Value();
326       }
327     }
328   };
329
330   struct Storage : std::conditional<
331                        std::is_trivially_destructible<Value>::value,
332                        StorageTriviallyDestructible,
333                        StorageNonTriviallyDestructible>::type {
334     bool hasValue() const noexcept {
335       return this->hasValue_;
336     }
337
338     Value* value_pointer() {
339       if (this->hasValue_) {
340         return launder(reinterpret_cast<Value*>(this->value_));
341       }
342       return nullptr;
343     }
344
345     Value const* value_pointer() const {
346       if (this->hasValue_) {
347         return launder(reinterpret_cast<Value const*>(this->value_));
348       }
349       return nullptr;
350     }
351
352     template <class... Args>
353     void construct(Args&&... args) {
354       new (raw_pointer()) Value(std::forward<Args>(args)...);
355       this->hasValue_ = true;
356     }
357
358    private:
359     void* raw_pointer() {
360       return static_cast<void*>(this->value_);
361     }
362   };
363
364   Storage storage_;
365 };
366
367 template <class T>
368 const T* get_pointer(const Optional<T>& opt) {
369   return opt.get_pointer();
370 }
371
372 template <class T>
373 T* get_pointer(Optional<T>& opt) {
374   return opt.get_pointer();
375 }
376
377 template <class T>
378 void swap(Optional<T>& a, Optional<T>& b) {
379   if (a.hasValue() && b.hasValue()) {
380     // both full
381     using std::swap;
382     swap(a.value(), b.value());
383   } else if (a.hasValue() || b.hasValue()) {
384     std::swap(a, b); // fall back to default implementation if they're mixed.
385   }
386 }
387
388 template <class T, class Opt = Optional<typename std::decay<T>::type>>
389 Opt make_optional(T&& v) {
390   return Opt(std::forward<T>(v));
391 }
392
393 ///////////////////////////////////////////////////////////////////////////////
394 // Comparisons.
395
396 template <class U, class V>
397 bool operator==(const Optional<U>& a, const V& b) {
398   return a.hasValue() && a.value() == b;
399 }
400
401 template <class U, class V>
402 bool operator!=(const Optional<U>& a, const V& b) {
403   return !(a == b);
404 }
405
406 template <class U, class V>
407 bool operator==(const U& a, const Optional<V>& b) {
408   return b.hasValue() && b.value() == a;
409 }
410
411 template <class U, class V>
412 bool operator!=(const U& a, const Optional<V>& b) {
413   return !(a == b);
414 }
415
416 template <class U, class V>
417 bool operator==(const Optional<U>& a, const Optional<V>& b) {
418   if (a.hasValue() != b.hasValue()) {
419     return false;
420   }
421   if (a.hasValue()) {
422     return a.value() == b.value();
423   }
424   return true;
425 }
426
427 template <class U, class V>
428 bool operator!=(const Optional<U>& a, const Optional<V>& b) {
429   return !(a == b);
430 }
431
432 template <class U, class V>
433 bool operator<(const Optional<U>& a, const Optional<V>& b) {
434   if (a.hasValue() != b.hasValue()) {
435     return a.hasValue() < b.hasValue();
436   }
437   if (a.hasValue()) {
438     return a.value() < b.value();
439   }
440   return false;
441 }
442
443 template <class U, class V>
444 bool operator>(const Optional<U>& a, const Optional<V>& b) {
445   return b < a;
446 }
447
448 template <class U, class V>
449 bool operator<=(const Optional<U>& a, const Optional<V>& b) {
450   return !(b < a);
451 }
452
453 template <class U, class V>
454 bool operator>=(const Optional<U>& a, const Optional<V>& b) {
455   return !(a < b);
456 }
457
458 // Suppress comparability of Optional<T> with T, despite implicit conversion.
459 template <class V>
460 bool operator<(const Optional<V>&, const V& other) = delete;
461 template <class V>
462 bool operator<=(const Optional<V>&, const V& other) = delete;
463 template <class V>
464 bool operator>=(const Optional<V>&, const V& other) = delete;
465 template <class V>
466 bool operator>(const Optional<V>&, const V& other) = delete;
467 template <class V>
468 bool operator<(const V& other, const Optional<V>&) = delete;
469 template <class V>
470 bool operator<=(const V& other, const Optional<V>&) = delete;
471 template <class V>
472 bool operator>=(const V& other, const Optional<V>&) = delete;
473 template <class V>
474 bool operator>(const V& other, const Optional<V>&) = delete;
475
476 // Comparisons with none
477 template <class V>
478 bool operator==(const Optional<V>& a, None) noexcept {
479   return !a.hasValue();
480 }
481 template <class V>
482 bool operator==(None, const Optional<V>& a) noexcept {
483   return !a.hasValue();
484 }
485 template <class V>
486 bool operator<(const Optional<V>&, None) noexcept {
487   return false;
488 }
489 template <class V>
490 bool operator<(None, const Optional<V>& a) noexcept {
491   return a.hasValue();
492 }
493 template <class V>
494 bool operator>(const Optional<V>& a, None) noexcept {
495   return a.hasValue();
496 }
497 template <class V>
498 bool operator>(None, const Optional<V>&) noexcept {
499   return false;
500 }
501 template <class V>
502 bool operator<=(None, const Optional<V>&) noexcept {
503   return true;
504 }
505 template <class V>
506 bool operator<=(const Optional<V>& a, None) noexcept {
507   return !a.hasValue();
508 }
509 template <class V>
510 bool operator>=(const Optional<V>&, None) noexcept {
511   return true;
512 }
513 template <class V>
514 bool operator>=(None, const Optional<V>& a) noexcept {
515   return !a.hasValue();
516 }
517
518 ///////////////////////////////////////////////////////////////////////////////
519
520 } // namespace folly
521
522 // Allow usage of Optional<T> in std::unordered_map and std::unordered_set
523 FOLLY_NAMESPACE_STD_BEGIN
524 template <class T>
525 struct hash<folly::Optional<T>> {
526   size_t operator()(folly::Optional<T> const& obj) const {
527     if (!obj.hasValue()) {
528       return 0;
529     }
530     return hash<typename remove_const<T>::type>()(*obj);
531   }
532 };
533 FOLLY_NAMESPACE_STD_END
534
535 // Enable the use of folly::Optional with `co_await`
536 // Inspired by https://github.com/toby-allsopp/coroutine_monad
537 #if FOLLY_HAS_COROUTINES
538 #include <experimental/coroutine>
539
540 namespace folly {
541 namespace detail {
542 template <typename Value>
543 struct OptionalPromise;
544
545 template <typename Value>
546 struct OptionalPromiseReturn {
547   Optional<Value> storage_;
548   OptionalPromise<Value>* promise_;
549   /* implicit */ OptionalPromiseReturn(OptionalPromise<Value>& promise) noexcept
550       : promise_(&promise) {
551     promise.value_ = &storage_;
552   }
553   OptionalPromiseReturn(OptionalPromiseReturn&& that) noexcept
554       : OptionalPromiseReturn{*that.promise_} {}
555   ~OptionalPromiseReturn() {}
556   /* implicit */ operator Optional<Value>() & {
557     return std::move(storage_);
558   }
559 };
560
561 template <typename Value>
562 struct OptionalPromise {
563   Optional<Value>* value_ = nullptr;
564   OptionalPromise() = default;
565   OptionalPromise(OptionalPromise const&) = delete;
566   // This should work regardless of whether the compiler generates:
567   //    folly::Optional<Value> retobj{ p.get_return_object(); } // MSVC
568   // or:
569   //    auto retobj = p.get_return_object(); // clang
570   OptionalPromiseReturn<Value> get_return_object() noexcept {
571     return *this;
572   }
573   std::experimental::suspend_never initial_suspend() const noexcept {
574     return {};
575   }
576   std::experimental::suspend_never final_suspend() const {
577     return {};
578   }
579   template <typename U>
580   void return_value(U&& u) {
581     *value_ = static_cast<U&&>(u);
582   }
583   void unhandled_exception() {
584     // Technically, throwing from unhandled_exception is underspecified:
585     // https://github.com/GorNishanov/CoroutineWording/issues/17
586     throw;
587   }
588 };
589
590 template <typename Value>
591 struct OptionalAwaitable {
592   Optional<Value> o_;
593   bool await_ready() const noexcept {
594     return o_.hasValue();
595   }
596   Value await_resume() {
597     return o_.value();
598   }
599   template <typename CoroHandle>
600   void await_suspend(CoroHandle h) const {
601     // make sure the coroutine returns an empty Optional:
602     h.promise().value_->clear();
603     // Abort the rest of the coroutine:
604     h.destroy();
605   }
606 };
607 } // namespace detail
608
609 template <typename Value>
610 detail::OptionalAwaitable<Value>
611 /* implicit */ operator co_await(Optional<Value> o) {
612   return {std::move(o)};
613 }
614 } // namespace folly
615
616 // This makes std::optional<Value> useable as a coroutine return type..
617 FOLLY_NAMESPACE_STD_BEGIN
618 namespace experimental {
619 template <typename Value, typename... Args>
620 struct coroutine_traits<folly::Optional<Value>, Args...> {
621   using promise_type = folly::detail::OptionalPromise<Value>;
622 };
623 } // experimental
624 FOLLY_NAMESPACE_STD_END
625 #endif // FOLLY_HAS_COROUTINES