2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
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.
26 * Optional can be useful when a variable might or might not be needed:
28 * Optional<Logger> maybeLogger = ...;
30 * maybeLogger->log("hello");
33 * Optional enables a 'null' value for types which do not otherwise have
34 * nullability, especially useful for parameter passing:
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]);
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
51 * Optional<int> maybeInt = ...;
52 * if (int* v = get_pointer(maybeInt)) {
61 #include <type_traits>
64 #include <folly/Portability.h>
65 #include <folly/Traits.h>
66 #include <folly/Utility.h>
67 #include <folly/lang/Launder.h>
71 template <class Value>
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();
82 template <class Value>
83 struct OptionalPromiseReturn;
86 typedef int detail::NoneHelper::*None;
88 const None none = nullptr;
90 class OptionalEmptyException : public std::runtime_error {
92 OptionalEmptyException()
93 : std::runtime_error("Empty Optional cannot be unwrapped") {}
96 template <class Value>
99 typedef Value value_type;
102 !std::is_reference<Value>::value,
103 "Optional may not be used with reference types");
105 !std::is_abstract<Value>::value,
106 "Optional may not be used with abstract types");
108 FOLLY_CPP14_CONSTEXPR Optional() noexcept {}
110 Optional(const Optional& src) noexcept(
111 std::is_nothrow_copy_constructible<Value>::value) {
112 if (src.hasValue()) {
113 storage_.construct(src.value());
117 Optional(Optional&& src) noexcept(
118 std::is_nothrow_move_constructible<Value>::value) {
119 if (src.hasValue()) {
120 storage_.construct(std::move(src.value()));
125 FOLLY_CPP14_CONSTEXPR /* implicit */ Optional(const None&) noexcept {}
127 FOLLY_CPP14_CONSTEXPR /* implicit */ Optional(Value&& newValue) noexcept(
128 std::is_nothrow_move_constructible<Value>::value) {
129 storage_.construct(std::move(newValue));
132 FOLLY_CPP14_CONSTEXPR /* implicit */ Optional(const Value& newValue) noexcept(
133 std::is_nothrow_copy_constructible<Value>::value) {
134 storage_.construct(newValue);
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)...);
143 // Used only when an Optional is used with coroutines on MSVC
144 /* implicit */ Optional(const detail::OptionalPromiseReturn<Value>& p)
146 p.promise_->value_ = this;
149 void assign(const None&) {
153 void assign(Optional&& src) {
155 if (src.hasValue()) {
156 assign(std::move(src.value()));
164 void assign(const Optional& src) {
165 if (src.hasValue()) {
172 void assign(Value&& newValue) {
174 *storage_.value_pointer() = std::move(newValue);
176 storage_.construct(std::move(newValue));
180 void assign(const Value& newValue) {
182 *storage_.value_pointer() = newValue;
184 storage_.construct(newValue);
189 Optional& operator=(Arg&& arg) {
190 assign(std::forward<Arg>(arg));
194 Optional& operator=(Optional&& other) noexcept(
195 std::is_nothrow_move_assignable<Value>::value) {
196 assign(std::move(other));
200 Optional& operator=(const Optional& other) noexcept(
201 std::is_nothrow_copy_assignable<Value>::value) {
206 template <class... Args>
207 Value& emplace(Args&&... args) {
209 return storage_.construct(std::forward<Args>(args)...);
212 template <class U, class... Args>
213 typename std::enable_if<
214 std::is_constructible<Value, std::initializer_list<U>&, Args&&...>::value,
216 emplace(std::initializer_list<U> ilist, Args&&... args) {
218 return storage_.construct(ilist, std::forward<Args>(args)...);
221 void reset() noexcept {
225 void clear() noexcept {
229 void swap(Optional& that) noexcept(IsNothrowSwappable<Value>::value) {
230 if (hasValue() && that.hasValue()) {
232 swap(value(), that.value());
233 } else if (hasValue()) {
234 that.emplace(std::move(value()));
236 } else if (that.hasValue()) {
237 emplace(std::move(that.value()));
242 FOLLY_CPP14_CONSTEXPR const Value& value() const & {
244 return *storage_.value_pointer();
247 FOLLY_CPP14_CONSTEXPR Value& value() & {
249 return *storage_.value_pointer();
252 FOLLY_CPP14_CONSTEXPR Value&& value() && {
254 return std::move(*storage_.value_pointer());
257 FOLLY_CPP14_CONSTEXPR const Value&& value() const && {
259 return std::move(*storage_.value_pointer());
262 const Value* get_pointer() const & {
263 return storage_.value_pointer();
265 Value* get_pointer() & {
266 return storage_.value_pointer();
268 Value* get_pointer() && = delete;
270 FOLLY_CPP14_CONSTEXPR bool has_value() const noexcept {
271 return storage_.hasValue();
274 FOLLY_CPP14_CONSTEXPR bool hasValue() const noexcept {
278 FOLLY_CPP14_CONSTEXPR explicit operator bool() const noexcept {
282 FOLLY_CPP14_CONSTEXPR const Value& operator*() const & {
285 FOLLY_CPP14_CONSTEXPR Value& operator*() & {
288 FOLLY_CPP14_CONSTEXPR const Value&& operator*() const && {
289 return std::move(value());
291 FOLLY_CPP14_CONSTEXPR Value&& operator*() && {
292 return std::move(value());
295 FOLLY_CPP14_CONSTEXPR const Value* operator->() const {
298 FOLLY_CPP14_CONSTEXPR Value* operator->() {
302 // Return a copy of the value if set, or a given default if not.
304 FOLLY_CPP14_CONSTEXPR Value value_or(U&& dflt) const & {
305 if (storage_.hasValue()) {
306 return *storage_.value_pointer();
309 return std::forward<U>(dflt);
313 FOLLY_CPP14_CONSTEXPR Value value_or(U&& dflt) && {
314 if (storage_.hasValue()) {
315 return std::move(*storage_.value_pointer());
318 return std::forward<U>(dflt);
322 void require_value() const {
323 if (!storage_.hasValue()) {
324 detail::throw_optional_empty_exception();
328 struct StorageTriviallyDestructible {
331 typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
335 StorageTriviallyDestructible() : hasValue_{false} {}
341 struct StorageNonTriviallyDestructible {
344 typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
348 StorageNonTriviallyDestructible() : hasValue_{false} {}
349 ~StorageNonTriviallyDestructible() {
356 launder(reinterpret_cast<Value*>(value_))->~Value();
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_;
369 Value* value_pointer() {
370 if (this->hasValue_) {
371 return launder(reinterpret_cast<Value*>(this->value_));
376 Value const* value_pointer() const {
377 if (this->hasValue_) {
378 return launder(reinterpret_cast<Value const*>(this->value_));
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_));
391 void* raw_pointer() {
392 return static_cast<void*>(this->value_);
400 const T* get_pointer(const Optional<T>& opt) {
401 return opt.get_pointer();
405 T* get_pointer(Optional<T>& opt) {
406 return opt.get_pointer();
410 void swap(Optional<T>& a, Optional<T>& b) noexcept(noexcept(a.swap(b))) {
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));
419 ///////////////////////////////////////////////////////////////////////////////
422 template <class U, class V>
423 constexpr bool operator==(const Optional<U>& a, const V& b) {
424 return a.hasValue() && a.value() == b;
427 template <class U, class V>
428 constexpr bool operator!=(const Optional<U>& a, const V& b) {
432 template <class U, class V>
433 constexpr bool operator==(const U& a, const Optional<V>& b) {
434 return b.hasValue() && b.value() == a;
437 template <class U, class V>
438 constexpr bool operator!=(const U& a, const Optional<V>& b) {
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()) {
450 return a.value() == b.value();
455 template <class U, class V>
456 constexpr bool operator!=(const Optional<U>& a, const Optional<V>& b) {
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();
468 return a.value() < b.value();
473 template <class U, class V>
474 constexpr bool operator>(const Optional<U>& a, const Optional<V>& b) {
478 template <class U, class V>
479 constexpr bool operator<=(const Optional<U>& a, const Optional<V>& b) {
483 template <class U, class V>
484 constexpr bool operator>=(const Optional<U>& a, const Optional<V>& b) {
488 // Suppress comparability of Optional<T> with T, despite implicit conversion.
490 bool operator<(const Optional<V>&, const V& other) = delete;
492 bool operator<=(const Optional<V>&, const V& other) = delete;
494 bool operator>=(const Optional<V>&, const V& other) = delete;
496 bool operator>(const Optional<V>&, const V& other) = delete;
498 bool operator<(const V& other, const Optional<V>&) = delete;
500 bool operator<=(const V& other, const Optional<V>&) = delete;
502 bool operator>=(const V& other, const Optional<V>&) = delete;
504 bool operator>(const V& other, const Optional<V>&) = delete;
506 // Comparisons with none
508 constexpr bool operator==(const Optional<V>& a, None) noexcept {
509 return !a.hasValue();
512 constexpr bool operator==(None, const Optional<V>& a) noexcept {
513 return !a.hasValue();
516 constexpr bool operator<(const Optional<V>&, None) noexcept {
520 constexpr bool operator<(None, const Optional<V>& a) noexcept {
524 constexpr bool operator>(const Optional<V>& a, None) noexcept {
528 constexpr bool operator>(None, const Optional<V>&) noexcept {
532 constexpr bool operator<=(None, const Optional<V>&) noexcept {
536 constexpr bool operator<=(const Optional<V>& a, None) noexcept {
537 return !a.hasValue();
540 constexpr bool operator>=(const Optional<V>&, None) noexcept {
544 constexpr bool operator>=(None, const Optional<V>& a) noexcept {
545 return !a.hasValue();
548 ///////////////////////////////////////////////////////////////////////////////
552 // Allow usage of Optional<T> in std::unordered_map and std::unordered_set
553 FOLLY_NAMESPACE_STD_BEGIN
555 struct hash<folly::Optional<T>> {
556 size_t operator()(folly::Optional<T> const& obj) const {
557 if (!obj.hasValue()) {
560 return hash<typename remove_const<T>::type>()(*obj);
563 FOLLY_NAMESPACE_STD_END
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>
572 template <typename Value>
573 struct OptionalPromise;
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_;
583 OptionalPromiseReturn(OptionalPromiseReturn&& that) noexcept
584 : OptionalPromiseReturn{*that.promise_} {}
585 ~OptionalPromiseReturn() {}
586 /* implicit */ operator Optional<Value>() & {
587 return std::move(storage_);
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
599 // auto retobj = p.get_return_object(); // clang
600 OptionalPromiseReturn<Value> get_return_object() noexcept {
603 std::experimental::suspend_never initial_suspend() const noexcept {
606 std::experimental::suspend_never final_suspend() const {
609 template <typename U>
610 void return_value(U&& u) {
611 *value_ = static_cast<U&&>(u);
613 void unhandled_exception() {
614 // Technically, throwing from unhandled_exception is underspecified:
615 // https://github.com/GorNishanov/CoroutineWording/issues/17
620 template <typename Value>
621 struct OptionalAwaitable {
623 bool await_ready() const noexcept {
624 return o_.hasValue();
626 Value await_resume() {
627 return std::move(o_.value());
630 // Explicitly only allow suspension into an OptionalPromise
631 template <typename U>
633 std::experimental::coroutine_handle<OptionalPromise<U>> h) const {
634 // Abort the rest of the coroutine. resume() is not going to be called
638 } // namespace detail
640 template <typename Value>
641 detail::OptionalAwaitable<Value>
642 /* implicit */ operator co_await(Optional<Value> o) {
643 return {std::move(o)};
647 // This makes folly::Optional<Value> useable as a coroutine return type..
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>;
654 } // namespace experimental
656 #endif // FOLLY_HAS_COROUTINES