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