31e1f4fdc8b6a4a84ab7bdd952d63041971e65e2
[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   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   void emplace(Args&&... args) {
207     clear();
208     storage_.construct(std::forward<Args>(args)...);
209   }
210
211   void clear() {
212     storage_.clear();
213   }
214
215   FOLLY_CPP14_CONSTEXPR const Value& value() const & {
216     require_value();
217     return *storage_.value_pointer();
218   }
219
220   FOLLY_CPP14_CONSTEXPR Value& value() & {
221     require_value();
222     return *storage_.value_pointer();
223   }
224
225   FOLLY_CPP14_CONSTEXPR Value&& value() && {
226     require_value();
227     return std::move(*storage_.value_pointer());
228   }
229
230   FOLLY_CPP14_CONSTEXPR 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   FOLLY_CPP14_CONSTEXPR bool hasValue() const noexcept {
244     return storage_.hasValue();
245   }
246
247   FOLLY_CPP14_CONSTEXPR explicit operator bool() const noexcept {
248     return hasValue();
249   }
250
251   FOLLY_CPP14_CONSTEXPR const Value& operator*() const & {
252     return value();
253   }
254   FOLLY_CPP14_CONSTEXPR Value& operator*() & {
255     return value();
256   }
257   FOLLY_CPP14_CONSTEXPR const Value&& operator*() const && {
258     return std::move(value());
259   }
260   FOLLY_CPP14_CONSTEXPR Value&& operator*() && {
261     return std::move(value());
262   }
263
264   FOLLY_CPP14_CONSTEXPR const Value* operator->() const {
265     return &value();
266   }
267   FOLLY_CPP14_CONSTEXPR 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   FOLLY_CPP14_CONSTEXPR 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   FOLLY_CPP14_CONSTEXPR 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 constexpr 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 constexpr 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 constexpr bool operator!=(const Optional<U>& a, const V& b) {
403   return !(a == b);
404 }
405
406 template <class U, class V>
407 constexpr 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 constexpr bool operator!=(const U& a, const Optional<V>& b) {
413   return !(a == b);
414 }
415
416 template <class U, class V>
417 FOLLY_CPP14_CONSTEXPR bool operator==(
418     const Optional<U>& a,
419     const Optional<V>& b) {
420   if (a.hasValue() != b.hasValue()) {
421     return false;
422   }
423   if (a.hasValue()) {
424     return a.value() == b.value();
425   }
426   return true;
427 }
428
429 template <class U, class V>
430 constexpr bool operator!=(const Optional<U>& a, const Optional<V>& b) {
431   return !(a == b);
432 }
433
434 template <class U, class V>
435 FOLLY_CPP14_CONSTEXPR bool operator<(
436     const Optional<U>& a,
437     const Optional<V>& b) {
438   if (a.hasValue() != b.hasValue()) {
439     return a.hasValue() < b.hasValue();
440   }
441   if (a.hasValue()) {
442     return a.value() < b.value();
443   }
444   return false;
445 }
446
447 template <class U, class V>
448 constexpr bool operator>(const Optional<U>& a, const Optional<V>& b) {
449   return b < a;
450 }
451
452 template <class U, class V>
453 constexpr bool operator<=(const Optional<U>& a, const Optional<V>& b) {
454   return !(b < a);
455 }
456
457 template <class U, class V>
458 constexpr bool operator>=(const Optional<U>& a, const Optional<V>& b) {
459   return !(a < b);
460 }
461
462 // Suppress comparability of Optional<T> with T, despite implicit conversion.
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 Optional<V>&, const V& other) = delete;
469 template <class V>
470 bool operator>(const Optional<V>&, const V& other) = 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 template <class V>
476 bool operator>=(const V& other, const Optional<V>&) = delete;
477 template <class V>
478 bool operator>(const V& other, const Optional<V>&) = delete;
479
480 // Comparisons with none
481 template <class V>
482 constexpr bool operator==(const Optional<V>& a, None) noexcept {
483   return !a.hasValue();
484 }
485 template <class V>
486 constexpr bool operator==(None, const Optional<V>& a) noexcept {
487   return !a.hasValue();
488 }
489 template <class V>
490 constexpr bool operator<(const Optional<V>&, None) noexcept {
491   return false;
492 }
493 template <class V>
494 constexpr bool operator<(None, const Optional<V>& a) noexcept {
495   return a.hasValue();
496 }
497 template <class V>
498 constexpr bool operator>(const Optional<V>& a, None) noexcept {
499   return a.hasValue();
500 }
501 template <class V>
502 constexpr bool operator>(None, const Optional<V>&) noexcept {
503   return false;
504 }
505 template <class V>
506 constexpr bool operator<=(None, const Optional<V>&) noexcept {
507   return true;
508 }
509 template <class V>
510 constexpr bool operator<=(const Optional<V>& a, None) noexcept {
511   return !a.hasValue();
512 }
513 template <class V>
514 constexpr bool operator>=(const Optional<V>&, None) noexcept {
515   return true;
516 }
517 template <class V>
518 constexpr bool operator>=(None, const Optional<V>& a) noexcept {
519   return !a.hasValue();
520 }
521
522 ///////////////////////////////////////////////////////////////////////////////
523
524 } // namespace folly
525
526 // Allow usage of Optional<T> in std::unordered_map and std::unordered_set
527 FOLLY_NAMESPACE_STD_BEGIN
528 template <class T>
529 struct hash<folly::Optional<T>> {
530   size_t operator()(folly::Optional<T> const& obj) const {
531     if (!obj.hasValue()) {
532       return 0;
533     }
534     return hash<typename remove_const<T>::type>()(*obj);
535   }
536 };
537 FOLLY_NAMESPACE_STD_END
538
539 // Enable the use of folly::Optional with `co_await`
540 // Inspired by https://github.com/toby-allsopp/coroutine_monad
541 #if FOLLY_HAS_COROUTINES
542 #include <experimental/coroutine>
543
544 namespace folly {
545 namespace detail {
546 template <typename Value>
547 struct OptionalPromise;
548
549 template <typename Value>
550 struct OptionalPromiseReturn {
551   Optional<Value> storage_;
552   OptionalPromise<Value>* promise_;
553   /* implicit */ OptionalPromiseReturn(OptionalPromise<Value>& promise) noexcept
554       : promise_(&promise) {
555     promise.value_ = &storage_;
556   }
557   OptionalPromiseReturn(OptionalPromiseReturn&& that) noexcept
558       : OptionalPromiseReturn{*that.promise_} {}
559   ~OptionalPromiseReturn() {}
560   /* implicit */ operator Optional<Value>() & {
561     return std::move(storage_);
562   }
563 };
564
565 template <typename Value>
566 struct OptionalPromise {
567   Optional<Value>* value_ = nullptr;
568   OptionalPromise() = default;
569   OptionalPromise(OptionalPromise const&) = delete;
570   // This should work regardless of whether the compiler generates:
571   //    folly::Optional<Value> retobj{ p.get_return_object(); } // MSVC
572   // or:
573   //    auto retobj = p.get_return_object(); // clang
574   OptionalPromiseReturn<Value> get_return_object() noexcept {
575     return *this;
576   }
577   std::experimental::suspend_never initial_suspend() const noexcept {
578     return {};
579   }
580   std::experimental::suspend_never final_suspend() const {
581     return {};
582   }
583   template <typename U>
584   void return_value(U&& u) {
585     *value_ = static_cast<U&&>(u);
586   }
587   void unhandled_exception() {
588     // Technically, throwing from unhandled_exception is underspecified:
589     // https://github.com/GorNishanov/CoroutineWording/issues/17
590     throw;
591   }
592 };
593
594 template <typename Value>
595 struct OptionalAwaitable {
596   Optional<Value> o_;
597   bool await_ready() const noexcept {
598     return o_.hasValue();
599   }
600   Value await_resume() {
601     return std::move(o_.value());
602   }
603
604   // Explicitly only allow suspension into an OptionalPromise
605   template <typename U>
606   void await_suspend(
607       std::experimental::coroutine_handle<OptionalPromise<U>> h) const {
608     // Abort the rest of the coroutine. resume() is not going to be called
609     h.destroy();
610   }
611 };
612 } // namespace detail
613
614 template <typename Value>
615 detail::OptionalAwaitable<Value>
616 /* implicit */ operator co_await(Optional<Value> o) {
617   return {std::move(o)};
618 }
619 } // namespace folly
620
621 // This makes folly::Optional<Value> useable as a coroutine return type..
622 FOLLY_NAMESPACE_STD_BEGIN
623 namespace experimental {
624 template <typename Value, typename... Args>
625 struct coroutine_traits<folly::Optional<Value>, Args...> {
626   using promise_type = folly::detail::OptionalPromise<Value>;
627 };
628 } // namespace experimental
629 FOLLY_NAMESPACE_STD_END
630 #endif // FOLLY_HAS_COROUTINES