Fixes RCU test cases error (loads should use Consume ordering)
[folly.git] / folly / Optional.h
1 /*
2  * Copyright 2012-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 #pragma once
17
18 /*
19  * Optional - For conditional initialization of values, like boost::optional,
20  * but with support for move semantics and emplacement.  Reference type support
21  * has not been included due to limited use cases and potential confusion with
22  * semantics of assignment: Assigning to an optional reference could quite
23  * reasonably copy its value or redirect the reference.
24  *
25  * Optional can be useful when a variable might or might not be needed:
26  *
27  *  Optional<Logger> maybeLogger = ...;
28  *  if (maybeLogger) {
29  *    maybeLogger->log("hello");
30  *  }
31  *
32  * Optional enables a 'null' value for types which do not otherwise have
33  * nullability, especially useful for parameter passing:
34  *
35  * void testIterator(const unique_ptr<Iterator>& it,
36  *                   initializer_list<int> idsExpected,
37  *                   Optional<initializer_list<int>> ranksExpected = none) {
38  *   for (int i = 0; it->next(); ++i) {
39  *     EXPECT_EQ(it->doc().id(), idsExpected[i]);
40  *     if (ranksExpected) {
41  *       EXPECT_EQ(it->doc().rank(), (*ranksExpected)[i]);
42  *     }
43  *   }
44  * }
45  *
46  * Optional models OptionalPointee, so calling 'get_pointer(opt)' will return a
47  * pointer to nullptr if the 'opt' is empty, and a pointer to the value if it is
48  * not:
49  *
50  *  Optional<int> maybeInt = ...;
51  *  if (int* v = get_pointer(maybeInt)) {
52  *    cout << *v << endl;
53  *  }
54  */
55
56 #include <cstddef>
57 #include <functional>
58 #include <new>
59 #include <stdexcept>
60 #include <type_traits>
61 #include <utility>
62
63 #include <folly/Portability.h>
64 #include <folly/Traits.h>
65 #include <folly/Utility.h>
66 #include <folly/lang/Launder.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 FOLLY_EXPORT 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   FOLLY_CPP14_CONSTEXPR 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   FOLLY_CPP14_CONSTEXPR /* implicit */ Optional(const None&) noexcept {}
125
126   FOLLY_CPP14_CONSTEXPR /* implicit */ Optional(Value&& newValue) noexcept(
127       std::is_nothrow_move_constructible<Value>::value) {
128     storage_.construct(std::move(newValue));
129   }
130
131   FOLLY_CPP14_CONSTEXPR /* 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   FOLLY_CPP14_CONSTEXPR 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   Value& emplace(Args&&... args) {
207     clear();
208     return storage_.construct(std::forward<Args>(args)...);
209   }
210
211   template <class U, class... Args>
212   typename std::enable_if<
213       std::is_constructible<Value, std::initializer_list<U>&, Args&&...>::value,
214       Value&>::type
215   emplace(std::initializer_list<U> ilist, Args&&... args) {
216     clear();
217     return storage_.construct(ilist, std::forward<Args>(args)...);
218   }
219
220   void reset() noexcept {
221     storage_.clear();
222   }
223
224   void clear() noexcept {
225     reset();
226   }
227
228   void swap(Optional& that) noexcept(IsNothrowSwappable<Value>::value) {
229     if (hasValue() && that.hasValue()) {
230       using std::swap;
231       swap(value(), that.value());
232     } else if (hasValue()) {
233       that.emplace(std::move(value()));
234       reset();
235     } else if (that.hasValue()) {
236       emplace(std::move(that.value()));
237       that.reset();
238     }
239   }
240
241   FOLLY_CPP14_CONSTEXPR const Value& value() const & {
242     require_value();
243     return *storage_.value_pointer();
244   }
245
246   FOLLY_CPP14_CONSTEXPR Value& value() & {
247     require_value();
248     return *storage_.value_pointer();
249   }
250
251   FOLLY_CPP14_CONSTEXPR Value&& value() && {
252     require_value();
253     return std::move(*storage_.value_pointer());
254   }
255
256   FOLLY_CPP14_CONSTEXPR const Value&& value() const && {
257     require_value();
258     return std::move(*storage_.value_pointer());
259   }
260
261   const Value* get_pointer() const & {
262     return storage_.value_pointer();
263   }
264   Value* get_pointer() & {
265     return storage_.value_pointer();
266   }
267   Value* get_pointer() && = delete;
268
269   FOLLY_CPP14_CONSTEXPR bool has_value() const noexcept {
270     return storage_.hasValue();
271   }
272
273   FOLLY_CPP14_CONSTEXPR bool hasValue() const noexcept {
274     return has_value();
275   }
276
277   FOLLY_CPP14_CONSTEXPR explicit operator bool() const noexcept {
278     return has_value();
279   }
280
281   FOLLY_CPP14_CONSTEXPR const Value& operator*() const & {
282     return value();
283   }
284   FOLLY_CPP14_CONSTEXPR Value& operator*() & {
285     return value();
286   }
287   FOLLY_CPP14_CONSTEXPR const Value&& operator*() const && {
288     return std::move(value());
289   }
290   FOLLY_CPP14_CONSTEXPR Value&& operator*() && {
291     return std::move(value());
292   }
293
294   FOLLY_CPP14_CONSTEXPR const Value* operator->() const {
295     return &value();
296   }
297   FOLLY_CPP14_CONSTEXPR Value* operator->() {
298     return &value();
299   }
300
301   // Return a copy of the value if set, or a given default if not.
302   template <class U>
303   FOLLY_CPP14_CONSTEXPR Value value_or(U&& dflt) const & {
304     if (storage_.hasValue()) {
305       return *storage_.value_pointer();
306     }
307
308     return std::forward<U>(dflt);
309   }
310
311   template <class U>
312   FOLLY_CPP14_CONSTEXPR Value value_or(U&& dflt) && {
313     if (storage_.hasValue()) {
314       return std::move(*storage_.value_pointer());
315     }
316
317     return std::forward<U>(dflt);
318   }
319
320  private:
321   void require_value() const {
322     if (!storage_.hasValue()) {
323       detail::throw_optional_empty_exception();
324     }
325   }
326
327   struct StorageTriviallyDestructible {
328    protected:
329     bool hasValue_;
330     typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
331         value_[1];
332
333    public:
334     StorageTriviallyDestructible() : hasValue_{false} {}
335     void clear() {
336       hasValue_ = false;
337     }
338   };
339
340   struct StorageNonTriviallyDestructible {
341    protected:
342     bool hasValue_;
343     typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
344         value_[1];
345
346    public:
347     StorageNonTriviallyDestructible() : hasValue_{false} {}
348     ~StorageNonTriviallyDestructible() {
349       clear();
350     }
351
352     void clear() {
353       if (hasValue_) {
354         hasValue_ = false;
355         launder(reinterpret_cast<Value*>(value_))->~Value();
356       }
357     }
358   };
359
360   struct Storage : std::conditional<
361                        std::is_trivially_destructible<Value>::value,
362                        StorageTriviallyDestructible,
363                        StorageNonTriviallyDestructible>::type {
364     bool hasValue() const noexcept {
365       return this->hasValue_;
366     }
367
368     Value* value_pointer() {
369       if (this->hasValue_) {
370         return launder(reinterpret_cast<Value*>(this->value_));
371       }
372       return nullptr;
373     }
374
375     Value const* value_pointer() const {
376       if (this->hasValue_) {
377         return launder(reinterpret_cast<Value const*>(this->value_));
378       }
379       return nullptr;
380     }
381
382     template <class... Args>
383     Value& construct(Args&&... args) {
384       new (raw_pointer()) Value(std::forward<Args>(args)...);
385       this->hasValue_ = true;
386       return *launder(reinterpret_cast<Value*>(this->value_));
387     }
388
389    private:
390     void* raw_pointer() {
391       return static_cast<void*>(this->value_);
392     }
393   };
394
395   Storage storage_;
396 };
397
398 template <class T>
399 const T* get_pointer(const Optional<T>& opt) {
400   return opt.get_pointer();
401 }
402
403 template <class T>
404 T* get_pointer(Optional<T>& opt) {
405   return opt.get_pointer();
406 }
407
408 template <class T>
409 void swap(Optional<T>& a, Optional<T>& b) noexcept(noexcept(a.swap(b))) {
410   a.swap(b);
411 }
412
413 template <class T, class Opt = Optional<typename std::decay<T>::type>>
414 constexpr Opt make_optional(T&& v) {
415   return Opt(std::forward<T>(v));
416 }
417
418 ///////////////////////////////////////////////////////////////////////////////
419 // Comparisons.
420
421 template <class U, class V>
422 constexpr bool operator==(const Optional<U>& a, const V& b) {
423   return a.hasValue() && a.value() == b;
424 }
425
426 template <class U, class V>
427 constexpr bool operator!=(const Optional<U>& a, const V& b) {
428   return !(a == b);
429 }
430
431 template <class U, class V>
432 constexpr bool operator==(const U& a, const Optional<V>& b) {
433   return b.hasValue() && b.value() == a;
434 }
435
436 template <class U, class V>
437 constexpr bool operator!=(const U& a, const Optional<V>& b) {
438   return !(a == b);
439 }
440
441 template <class U, class V>
442 FOLLY_CPP14_CONSTEXPR bool operator==(
443     const Optional<U>& a,
444     const Optional<V>& b) {
445   if (a.hasValue() != b.hasValue()) {
446     return false;
447   }
448   if (a.hasValue()) {
449     return a.value() == b.value();
450   }
451   return true;
452 }
453
454 template <class U, class V>
455 constexpr bool operator!=(const Optional<U>& a, const Optional<V>& b) {
456   return !(a == b);
457 }
458
459 template <class U, class V>
460 FOLLY_CPP14_CONSTEXPR bool operator<(
461     const Optional<U>& a,
462     const Optional<V>& b) {
463   if (a.hasValue() != b.hasValue()) {
464     return a.hasValue() < b.hasValue();
465   }
466   if (a.hasValue()) {
467     return a.value() < b.value();
468   }
469   return false;
470 }
471
472 template <class U, class V>
473 constexpr bool operator>(const Optional<U>& a, const Optional<V>& b) {
474   return b < a;
475 }
476
477 template <class U, class V>
478 constexpr bool operator<=(const Optional<U>& a, const Optional<V>& b) {
479   return !(b < a);
480 }
481
482 template <class U, class V>
483 constexpr bool operator>=(const Optional<U>& a, const Optional<V>& b) {
484   return !(a < b);
485 }
486
487 // Suppress comparability of Optional<T> with T, despite implicit conversion.
488 template <class V>
489 bool operator<(const Optional<V>&, const V& other) = delete;
490 template <class V>
491 bool operator<=(const Optional<V>&, const V& other) = delete;
492 template <class V>
493 bool operator>=(const Optional<V>&, const V& other) = delete;
494 template <class V>
495 bool operator>(const Optional<V>&, const V& other) = delete;
496 template <class V>
497 bool operator<(const V& other, const Optional<V>&) = delete;
498 template <class V>
499 bool operator<=(const V& other, const Optional<V>&) = delete;
500 template <class V>
501 bool operator>=(const V& other, const Optional<V>&) = delete;
502 template <class V>
503 bool operator>(const V& other, const Optional<V>&) = delete;
504
505 // Comparisons with none
506 template <class V>
507 constexpr bool operator==(const Optional<V>& a, None) noexcept {
508   return !a.hasValue();
509 }
510 template <class V>
511 constexpr bool operator==(None, const Optional<V>& a) noexcept {
512   return !a.hasValue();
513 }
514 template <class V>
515 constexpr bool operator<(const Optional<V>&, None) noexcept {
516   return false;
517 }
518 template <class V>
519 constexpr bool operator<(None, const Optional<V>& a) noexcept {
520   return a.hasValue();
521 }
522 template <class V>
523 constexpr bool operator>(const Optional<V>& a, None) noexcept {
524   return a.hasValue();
525 }
526 template <class V>
527 constexpr bool operator>(None, const Optional<V>&) noexcept {
528   return false;
529 }
530 template <class V>
531 constexpr bool operator<=(None, const Optional<V>&) noexcept {
532   return true;
533 }
534 template <class V>
535 constexpr bool operator<=(const Optional<V>& a, None) noexcept {
536   return !a.hasValue();
537 }
538 template <class V>
539 constexpr bool operator>=(const Optional<V>&, None) noexcept {
540   return true;
541 }
542 template <class V>
543 constexpr bool operator>=(None, const Optional<V>& a) noexcept {
544   return !a.hasValue();
545 }
546
547 ///////////////////////////////////////////////////////////////////////////////
548
549 } // namespace folly
550
551 // Allow usage of Optional<T> in std::unordered_map and std::unordered_set
552 FOLLY_NAMESPACE_STD_BEGIN
553 template <class T>
554 struct hash<folly::Optional<T>> {
555   size_t operator()(folly::Optional<T> const& obj) const {
556     if (!obj.hasValue()) {
557       return 0;
558     }
559     return hash<typename remove_const<T>::type>()(*obj);
560   }
561 };
562 FOLLY_NAMESPACE_STD_END
563
564 // Enable the use of folly::Optional with `co_await`
565 // Inspired by https://github.com/toby-allsopp/coroutine_monad
566 #if FOLLY_HAS_COROUTINES
567 #include <experimental/coroutine>
568
569 namespace folly {
570 namespace detail {
571 template <typename Value>
572 struct OptionalPromise;
573
574 template <typename Value>
575 struct OptionalPromiseReturn {
576   Optional<Value> storage_;
577   OptionalPromise<Value>* promise_;
578   /* implicit */ OptionalPromiseReturn(OptionalPromise<Value>& promise) noexcept
579       : promise_(&promise) {
580     promise.value_ = &storage_;
581   }
582   OptionalPromiseReturn(OptionalPromiseReturn&& that) noexcept
583       : OptionalPromiseReturn{*that.promise_} {}
584   ~OptionalPromiseReturn() {}
585   /* implicit */ operator Optional<Value>() & {
586     return std::move(storage_);
587   }
588 };
589
590 template <typename Value>
591 struct OptionalPromise {
592   Optional<Value>* value_ = nullptr;
593   OptionalPromise() = default;
594   OptionalPromise(OptionalPromise const&) = delete;
595   // This should work regardless of whether the compiler generates:
596   //    folly::Optional<Value> retobj{ p.get_return_object(); } // MSVC
597   // or:
598   //    auto retobj = p.get_return_object(); // clang
599   OptionalPromiseReturn<Value> get_return_object() noexcept {
600     return *this;
601   }
602   std::experimental::suspend_never initial_suspend() const noexcept {
603     return {};
604   }
605   std::experimental::suspend_never final_suspend() const {
606     return {};
607   }
608   template <typename U>
609   void return_value(U&& u) {
610     *value_ = static_cast<U&&>(u);
611   }
612   void unhandled_exception() {
613     // Technically, throwing from unhandled_exception is underspecified:
614     // https://github.com/GorNishanov/CoroutineWording/issues/17
615     throw;
616   }
617 };
618
619 template <typename Value>
620 struct OptionalAwaitable {
621   Optional<Value> o_;
622   bool await_ready() const noexcept {
623     return o_.hasValue();
624   }
625   Value await_resume() {
626     return std::move(o_.value());
627   }
628
629   // Explicitly only allow suspension into an OptionalPromise
630   template <typename U>
631   void await_suspend(
632       std::experimental::coroutine_handle<OptionalPromise<U>> h) const {
633     // Abort the rest of the coroutine. resume() is not going to be called
634     h.destroy();
635   }
636 };
637 } // namespace detail
638
639 template <typename Value>
640 detail::OptionalAwaitable<Value>
641 /* implicit */ operator co_await(Optional<Value> o) {
642   return {std::move(o)};
643 }
644 } // namespace folly
645
646 // This makes folly::Optional<Value> useable as a coroutine return type..
647 namespace std {
648 namespace experimental {
649 template <typename Value, typename... Args>
650 struct coroutine_traits<folly::Optional<Value>, Args...> {
651   using promise_type = folly::detail::OptionalPromise<Value>;
652 };
653 } // namespace experimental
654 } // namespace std
655 #endif // FOLLY_HAS_COROUTINES