2 * Copyright 2012-present 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.
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.
25 * Optional can be useful when a variable might or might not be needed:
27 * Optional<Logger> maybeLogger = ...;
29 * maybeLogger->log("hello");
32 * Optional enables a 'null' value for types which do not otherwise have
33 * nullability, especially useful for parameter passing:
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]);
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
50 * Optional<int> maybeInt = ...;
51 * if (int* v = get_pointer(maybeInt)) {
60 #include <type_traits>
63 #include <folly/Portability.h>
64 #include <folly/Traits.h>
65 #include <folly/Utility.h>
66 #include <folly/lang/Launder.h>
70 template <class Value>
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();
81 template <class Value>
82 struct OptionalPromiseReturn;
85 typedef int detail::NoneHelper::*None;
87 const None none = nullptr;
89 class FOLLY_EXPORT OptionalEmptyException : public std::runtime_error {
91 OptionalEmptyException()
92 : std::runtime_error("Empty Optional cannot be unwrapped") {}
95 template <class Value>
98 typedef Value value_type;
101 !std::is_reference<Value>::value,
102 "Optional may not be used with reference types");
104 !std::is_abstract<Value>::value,
105 "Optional may not be used with abstract types");
107 FOLLY_CPP14_CONSTEXPR Optional() noexcept {}
109 Optional(const Optional& src) noexcept(
110 std::is_nothrow_copy_constructible<Value>::value) {
111 if (src.hasValue()) {
112 storage_.construct(src.value());
116 Optional(Optional&& src) noexcept(
117 std::is_nothrow_move_constructible<Value>::value) {
118 if (src.hasValue()) {
119 storage_.construct(std::move(src.value()));
124 FOLLY_CPP14_CONSTEXPR /* implicit */ Optional(const None&) noexcept {}
126 FOLLY_CPP14_CONSTEXPR /* implicit */ Optional(Value&& newValue) noexcept(
127 std::is_nothrow_move_constructible<Value>::value) {
128 storage_.construct(std::move(newValue));
131 FOLLY_CPP14_CONSTEXPR /* implicit */ Optional(const Value& newValue) noexcept(
132 std::is_nothrow_copy_constructible<Value>::value) {
133 storage_.construct(newValue);
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)...);
142 // Used only when an Optional is used with coroutines on MSVC
143 /* implicit */ Optional(const detail::OptionalPromiseReturn<Value>& p)
145 p.promise_->value_ = this;
148 void assign(const None&) {
152 void assign(Optional&& src) {
154 if (src.hasValue()) {
155 assign(std::move(src.value()));
163 void assign(const Optional& src) {
164 if (src.hasValue()) {
171 void assign(Value&& newValue) {
173 *storage_.value_pointer() = std::move(newValue);
175 storage_.construct(std::move(newValue));
179 void assign(const Value& newValue) {
181 *storage_.value_pointer() = newValue;
183 storage_.construct(newValue);
188 Optional& operator=(Arg&& arg) {
189 assign(std::forward<Arg>(arg));
193 Optional& operator=(Optional&& other) noexcept(
194 std::is_nothrow_move_assignable<Value>::value) {
195 assign(std::move(other));
199 Optional& operator=(const Optional& other) noexcept(
200 std::is_nothrow_copy_assignable<Value>::value) {
205 template <class... Args>
206 Value& emplace(Args&&... args) {
208 return storage_.construct(std::forward<Args>(args)...);
211 template <class U, class... Args>
212 typename std::enable_if<
213 std::is_constructible<Value, std::initializer_list<U>&, Args&&...>::value,
215 emplace(std::initializer_list<U> ilist, Args&&... args) {
217 return storage_.construct(ilist, std::forward<Args>(args)...);
220 void reset() noexcept {
224 void clear() noexcept {
228 void swap(Optional& that) noexcept(IsNothrowSwappable<Value>::value) {
229 if (hasValue() && that.hasValue()) {
231 swap(value(), that.value());
232 } else if (hasValue()) {
233 that.emplace(std::move(value()));
235 } else if (that.hasValue()) {
236 emplace(std::move(that.value()));
241 FOLLY_CPP14_CONSTEXPR const Value& value() const & {
243 return *storage_.value_pointer();
246 FOLLY_CPP14_CONSTEXPR Value& value() & {
248 return *storage_.value_pointer();
251 FOLLY_CPP14_CONSTEXPR Value&& value() && {
253 return std::move(*storage_.value_pointer());
256 FOLLY_CPP14_CONSTEXPR const Value&& value() const && {
258 return std::move(*storage_.value_pointer());
261 const Value* get_pointer() const & {
262 return storage_.value_pointer();
264 Value* get_pointer() & {
265 return storage_.value_pointer();
267 Value* get_pointer() && = delete;
269 FOLLY_CPP14_CONSTEXPR bool has_value() const noexcept {
270 return storage_.hasValue();
273 FOLLY_CPP14_CONSTEXPR bool hasValue() const noexcept {
277 FOLLY_CPP14_CONSTEXPR explicit operator bool() const noexcept {
281 FOLLY_CPP14_CONSTEXPR const Value& operator*() const & {
284 FOLLY_CPP14_CONSTEXPR Value& operator*() & {
287 FOLLY_CPP14_CONSTEXPR const Value&& operator*() const && {
288 return std::move(value());
290 FOLLY_CPP14_CONSTEXPR Value&& operator*() && {
291 return std::move(value());
294 FOLLY_CPP14_CONSTEXPR const Value* operator->() const {
297 FOLLY_CPP14_CONSTEXPR Value* operator->() {
301 // Return a copy of the value if set, or a given default if not.
303 FOLLY_CPP14_CONSTEXPR Value value_or(U&& dflt) const & {
304 if (storage_.hasValue()) {
305 return *storage_.value_pointer();
308 return std::forward<U>(dflt);
312 FOLLY_CPP14_CONSTEXPR Value value_or(U&& dflt) && {
313 if (storage_.hasValue()) {
314 return std::move(*storage_.value_pointer());
317 return std::forward<U>(dflt);
321 void require_value() const {
322 if (!storage_.hasValue()) {
323 detail::throw_optional_empty_exception();
327 struct StorageTriviallyDestructible {
330 typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
334 StorageTriviallyDestructible() : hasValue_{false} {}
340 struct StorageNonTriviallyDestructible {
343 typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
347 StorageNonTriviallyDestructible() : hasValue_{false} {}
348 ~StorageNonTriviallyDestructible() {
355 launder(reinterpret_cast<Value*>(value_))->~Value();
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_;
368 Value* value_pointer() {
369 if (this->hasValue_) {
370 return launder(reinterpret_cast<Value*>(this->value_));
375 Value const* value_pointer() const {
376 if (this->hasValue_) {
377 return launder(reinterpret_cast<Value const*>(this->value_));
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_));
390 void* raw_pointer() {
391 return static_cast<void*>(this->value_);
399 const T* get_pointer(const Optional<T>& opt) {
400 return opt.get_pointer();
404 T* get_pointer(Optional<T>& opt) {
405 return opt.get_pointer();
409 void swap(Optional<T>& a, Optional<T>& b) noexcept(noexcept(a.swap(b))) {
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));
418 ///////////////////////////////////////////////////////////////////////////////
421 template <class U, class V>
422 constexpr bool operator==(const Optional<U>& a, const V& b) {
423 return a.hasValue() && a.value() == b;
426 template <class U, class V>
427 constexpr bool operator!=(const Optional<U>& a, const V& b) {
431 template <class U, class V>
432 constexpr bool operator==(const U& a, const Optional<V>& b) {
433 return b.hasValue() && b.value() == a;
436 template <class U, class V>
437 constexpr bool operator!=(const U& a, const Optional<V>& b) {
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()) {
449 return a.value() == b.value();
454 template <class U, class V>
455 constexpr bool operator!=(const Optional<U>& a, const Optional<V>& b) {
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();
467 return a.value() < b.value();
472 template <class U, class V>
473 constexpr bool operator>(const Optional<U>& a, const Optional<V>& b) {
477 template <class U, class V>
478 constexpr bool operator<=(const Optional<U>& a, const Optional<V>& b) {
482 template <class U, class V>
483 constexpr bool operator>=(const Optional<U>& a, const Optional<V>& b) {
487 // Suppress comparability of Optional<T> with T, despite implicit conversion.
489 bool operator<(const Optional<V>&, const V& other) = delete;
491 bool operator<=(const Optional<V>&, const V& other) = delete;
493 bool operator>=(const Optional<V>&, const V& other) = delete;
495 bool operator>(const Optional<V>&, const V& other) = delete;
497 bool operator<(const V& other, const Optional<V>&) = delete;
499 bool operator<=(const V& other, const Optional<V>&) = delete;
501 bool operator>=(const V& other, const Optional<V>&) = delete;
503 bool operator>(const V& other, const Optional<V>&) = delete;
505 // Comparisons with none
507 constexpr bool operator==(const Optional<V>& a, None) noexcept {
508 return !a.hasValue();
511 constexpr bool operator==(None, const Optional<V>& a) noexcept {
512 return !a.hasValue();
515 constexpr bool operator<(const Optional<V>&, None) noexcept {
519 constexpr bool operator<(None, const Optional<V>& a) noexcept {
523 constexpr bool operator>(const Optional<V>& a, None) noexcept {
527 constexpr bool operator>(None, const Optional<V>&) noexcept {
531 constexpr bool operator<=(None, const Optional<V>&) noexcept {
535 constexpr bool operator<=(const Optional<V>& a, None) noexcept {
536 return !a.hasValue();
539 constexpr bool operator>=(const Optional<V>&, None) noexcept {
543 constexpr bool operator>=(None, const Optional<V>& a) noexcept {
544 return !a.hasValue();
547 ///////////////////////////////////////////////////////////////////////////////
551 // Allow usage of Optional<T> in std::unordered_map and std::unordered_set
552 FOLLY_NAMESPACE_STD_BEGIN
554 struct hash<folly::Optional<T>> {
555 size_t operator()(folly::Optional<T> const& obj) const {
556 if (!obj.hasValue()) {
559 return hash<typename remove_const<T>::type>()(*obj);
562 FOLLY_NAMESPACE_STD_END
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>
571 template <typename Value>
572 struct OptionalPromise;
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_;
582 OptionalPromiseReturn(OptionalPromiseReturn&& that) noexcept
583 : OptionalPromiseReturn{*that.promise_} {}
584 ~OptionalPromiseReturn() {}
585 /* implicit */ operator Optional<Value>() & {
586 return std::move(storage_);
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
598 // auto retobj = p.get_return_object(); // clang
599 OptionalPromiseReturn<Value> get_return_object() noexcept {
602 std::experimental::suspend_never initial_suspend() const noexcept {
605 std::experimental::suspend_never final_suspend() const {
608 template <typename U>
609 void return_value(U&& u) {
610 *value_ = static_cast<U&&>(u);
612 void unhandled_exception() {
613 // Technically, throwing from unhandled_exception is underspecified:
614 // https://github.com/GorNishanov/CoroutineWording/issues/17
619 template <typename Value>
620 struct OptionalAwaitable {
622 bool await_ready() const noexcept {
623 return o_.hasValue();
625 Value await_resume() {
626 return std::move(o_.value());
629 // Explicitly only allow suspension into an OptionalPromise
630 template <typename U>
632 std::experimental::coroutine_handle<OptionalPromise<U>> h) const {
633 // Abort the rest of the coroutine. resume() is not going to be called
637 } // namespace detail
639 template <typename Value>
640 detail::OptionalAwaitable<Value>
641 /* implicit */ operator co_await(Optional<Value> o) {
642 return {std::move(o)};
646 // This makes folly::Optional<Value> useable as a coroutine return type..
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>;
653 } // namespace experimental
655 #endif // FOLLY_HAS_COROUTINES