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/Launder.h>
65 #include <folly/Portability.h>
66 #include <folly/Utility.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 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 void emplace(Args&&... args) {
208 storage_.construct(std::forward<Args>(args)...);
215 FOLLY_CPP14_CONSTEXPR const Value& value() const & {
217 return *storage_.value_pointer();
220 FOLLY_CPP14_CONSTEXPR Value& value() & {
222 return *storage_.value_pointer();
225 FOLLY_CPP14_CONSTEXPR Value&& value() && {
227 return std::move(*storage_.value_pointer());
230 FOLLY_CPP14_CONSTEXPR const Value&& value() const && {
232 return std::move(*storage_.value_pointer());
235 const Value* get_pointer() const & {
236 return storage_.value_pointer();
238 Value* get_pointer() & {
239 return storage_.value_pointer();
241 Value* get_pointer() && = delete;
243 FOLLY_CPP14_CONSTEXPR bool hasValue() const noexcept {
244 return storage_.hasValue();
247 FOLLY_CPP14_CONSTEXPR explicit operator bool() const noexcept {
251 FOLLY_CPP14_CONSTEXPR const Value& operator*() const & {
254 FOLLY_CPP14_CONSTEXPR Value& operator*() & {
257 FOLLY_CPP14_CONSTEXPR const Value&& operator*() const && {
258 return std::move(value());
260 FOLLY_CPP14_CONSTEXPR Value&& operator*() && {
261 return std::move(value());
264 FOLLY_CPP14_CONSTEXPR const Value* operator->() const {
267 FOLLY_CPP14_CONSTEXPR Value* operator->() {
271 // Return a copy of the value if set, or a given default if not.
273 FOLLY_CPP14_CONSTEXPR Value value_or(U&& dflt) const & {
274 if (storage_.hasValue()) {
275 return *storage_.value_pointer();
278 return std::forward<U>(dflt);
282 FOLLY_CPP14_CONSTEXPR Value value_or(U&& dflt) && {
283 if (storage_.hasValue()) {
284 return std::move(*storage_.value_pointer());
287 return std::forward<U>(dflt);
291 void require_value() const {
292 if (!storage_.hasValue()) {
293 detail::throw_optional_empty_exception();
297 struct StorageTriviallyDestructible {
300 typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
304 StorageTriviallyDestructible() : hasValue_{false} {}
310 struct StorageNonTriviallyDestructible {
313 typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
317 StorageNonTriviallyDestructible() : hasValue_{false} {}
318 ~StorageNonTriviallyDestructible() {
325 launder(reinterpret_cast<Value*>(value_))->~Value();
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_;
338 Value* value_pointer() {
339 if (this->hasValue_) {
340 return launder(reinterpret_cast<Value*>(this->value_));
345 Value const* value_pointer() const {
346 if (this->hasValue_) {
347 return launder(reinterpret_cast<Value const*>(this->value_));
352 template <class... Args>
353 void construct(Args&&... args) {
354 new (raw_pointer()) Value(std::forward<Args>(args)...);
355 this->hasValue_ = true;
359 void* raw_pointer() {
360 return static_cast<void*>(this->value_);
368 const T* get_pointer(const Optional<T>& opt) {
369 return opt.get_pointer();
373 T* get_pointer(Optional<T>& opt) {
374 return opt.get_pointer();
378 void swap(Optional<T>& a, Optional<T>& b) {
379 if (a.hasValue() && b.hasValue()) {
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.
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));
393 ///////////////////////////////////////////////////////////////////////////////
396 template <class U, class V>
397 constexpr bool operator==(const Optional<U>& a, const V& b) {
398 return a.hasValue() && a.value() == b;
401 template <class U, class V>
402 constexpr bool operator!=(const Optional<U>& a, const V& b) {
406 template <class U, class V>
407 constexpr bool operator==(const U& a, const Optional<V>& b) {
408 return b.hasValue() && b.value() == a;
411 template <class U, class V>
412 constexpr bool operator!=(const U& a, const Optional<V>& b) {
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()) {
424 return a.value() == b.value();
429 template <class U, class V>
430 constexpr bool operator!=(const Optional<U>& a, const Optional<V>& b) {
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();
442 return a.value() < b.value();
447 template <class U, class V>
448 constexpr bool operator>(const Optional<U>& a, const Optional<V>& b) {
452 template <class U, class V>
453 constexpr bool operator<=(const Optional<U>& a, const Optional<V>& b) {
457 template <class U, class V>
458 constexpr bool operator>=(const Optional<U>& a, const Optional<V>& b) {
462 // Suppress comparability of Optional<T> with T, despite implicit conversion.
464 bool operator<(const Optional<V>&, const V& other) = delete;
466 bool operator<=(const Optional<V>&, const V& other) = delete;
468 bool operator>=(const Optional<V>&, const V& other) = delete;
470 bool operator>(const Optional<V>&, const V& other) = delete;
472 bool operator<(const V& other, const Optional<V>&) = delete;
474 bool operator<=(const V& other, const Optional<V>&) = delete;
476 bool operator>=(const V& other, const Optional<V>&) = delete;
478 bool operator>(const V& other, const Optional<V>&) = delete;
480 // Comparisons with none
482 constexpr bool operator==(const Optional<V>& a, None) noexcept {
483 return !a.hasValue();
486 constexpr bool operator==(None, const Optional<V>& a) noexcept {
487 return !a.hasValue();
490 constexpr bool operator<(const Optional<V>&, None) noexcept {
494 constexpr bool operator<(None, const Optional<V>& a) noexcept {
498 constexpr bool operator>(const Optional<V>& a, None) noexcept {
502 constexpr bool operator>(None, const Optional<V>&) noexcept {
506 constexpr bool operator<=(None, const Optional<V>&) noexcept {
510 constexpr bool operator<=(const Optional<V>& a, None) noexcept {
511 return !a.hasValue();
514 constexpr bool operator>=(const Optional<V>&, None) noexcept {
518 constexpr bool operator>=(None, const Optional<V>& a) noexcept {
519 return !a.hasValue();
522 ///////////////////////////////////////////////////////////////////////////////
526 // Allow usage of Optional<T> in std::unordered_map and std::unordered_set
527 FOLLY_NAMESPACE_STD_BEGIN
529 struct hash<folly::Optional<T>> {
530 size_t operator()(folly::Optional<T> const& obj) const {
531 if (!obj.hasValue()) {
534 return hash<typename remove_const<T>::type>()(*obj);
537 FOLLY_NAMESPACE_STD_END
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>
546 template <typename Value>
547 struct OptionalPromise;
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_;
557 OptionalPromiseReturn(OptionalPromiseReturn&& that) noexcept
558 : OptionalPromiseReturn{*that.promise_} {}
559 ~OptionalPromiseReturn() {}
560 /* implicit */ operator Optional<Value>() & {
561 return std::move(storage_);
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
573 // auto retobj = p.get_return_object(); // clang
574 OptionalPromiseReturn<Value> get_return_object() noexcept {
577 std::experimental::suspend_never initial_suspend() const noexcept {
580 std::experimental::suspend_never final_suspend() const {
583 template <typename U>
584 void return_value(U&& u) {
585 *value_ = static_cast<U&&>(u);
587 void unhandled_exception() {
588 // Technically, throwing from unhandled_exception is underspecified:
589 // https://github.com/GorNishanov/CoroutineWording/issues/17
594 template <typename Value>
595 struct OptionalAwaitable {
597 bool await_ready() const noexcept {
598 return o_.hasValue();
600 Value await_resume() {
601 return std::move(o_.value());
604 // Explicitly only allow suspension into an OptionalPromise
605 template <typename U>
607 std::experimental::coroutine_handle<OptionalPromise<U>> h) const {
608 // Abort the rest of the coroutine. resume() is not going to be called
612 } // namespace detail
614 template <typename Value>
615 detail::OptionalAwaitable<Value>
616 /* implicit */ operator co_await(Optional<Value> o) {
617 return {std::move(o)};
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>;
629 FOLLY_NAMESPACE_STD_END
630 #endif // FOLLY_HAS_COROUTINES