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 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 /* implicit */ Optional(const None&) noexcept {}
126 /* implicit */ Optional(Value&& newValue) noexcept(
127 std::is_nothrow_move_constructible<Value>::value) {
128 storage_.construct(std::move(newValue));
131 /* implicit */ Optional(const Value& newValue) noexcept(
132 std::is_nothrow_copy_constructible<Value>::value) {
133 storage_.construct(newValue);
136 template <typename... Args>
137 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 const Value& value() const & {
217 return *storage_.value_pointer();
222 return *storage_.value_pointer();
227 return std::move(*storage_.value_pointer());
230 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 bool hasValue() const noexcept {
244 return storage_.hasValue();
247 explicit operator bool() const noexcept {
251 const Value& operator*() const & {
254 Value& operator*() & {
257 const Value&& operator*() const && {
258 return std::move(value());
260 Value&& operator*() && {
261 return std::move(value());
264 const Value* operator->() const {
267 Value* operator->() {
271 // Return a copy of the value if set, or a given default if not.
273 Value value_or(U&& dflt) const & {
274 if (storage_.hasValue()) {
275 return *storage_.value_pointer();
278 return std::forward<U>(dflt);
282 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 Opt make_optional(T&& v) {
390 return Opt(std::forward<T>(v));
393 ///////////////////////////////////////////////////////////////////////////////
396 template <class U, class V>
397 bool operator==(const Optional<U>& a, const V& b) {
398 return a.hasValue() && a.value() == b;
401 template <class U, class V>
402 bool operator!=(const Optional<U>& a, const V& b) {
406 template <class U, class V>
407 bool operator==(const U& a, const Optional<V>& b) {
408 return b.hasValue() && b.value() == a;
411 template <class U, class V>
412 bool operator!=(const U& a, const Optional<V>& b) {
416 template <class U, class V>
417 bool operator==(const Optional<U>& a, const Optional<V>& b) {
418 if (a.hasValue() != b.hasValue()) {
422 return a.value() == b.value();
427 template <class U, class V>
428 bool operator!=(const Optional<U>& a, const Optional<V>& b) {
432 template <class U, class V>
433 bool operator<(const Optional<U>& a, const Optional<V>& b) {
434 if (a.hasValue() != b.hasValue()) {
435 return a.hasValue() < b.hasValue();
438 return a.value() < b.value();
443 template <class U, class V>
444 bool operator>(const Optional<U>& a, const Optional<V>& b) {
448 template <class U, class V>
449 bool operator<=(const Optional<U>& a, const Optional<V>& b) {
453 template <class U, class V>
454 bool operator>=(const Optional<U>& a, const Optional<V>& b) {
458 // Suppress comparability of Optional<T> with T, despite implicit conversion.
460 bool operator<(const Optional<V>&, const V& other) = delete;
462 bool operator<=(const Optional<V>&, const V& other) = delete;
464 bool operator>=(const Optional<V>&, const V& other) = delete;
466 bool operator>(const Optional<V>&, const V& other) = delete;
468 bool operator<(const V& other, const Optional<V>&) = delete;
470 bool operator<=(const V& other, const Optional<V>&) = delete;
472 bool operator>=(const V& other, const Optional<V>&) = delete;
474 bool operator>(const V& other, const Optional<V>&) = delete;
476 // Comparisons with none
478 bool operator==(const Optional<V>& a, None) noexcept {
479 return !a.hasValue();
482 bool operator==(None, const Optional<V>& a) noexcept {
483 return !a.hasValue();
486 bool operator<(const Optional<V>&, None) noexcept {
490 bool operator<(None, const Optional<V>& a) noexcept {
494 bool operator>(const Optional<V>& a, None) noexcept {
498 bool operator>(None, const Optional<V>&) noexcept {
502 bool operator<=(None, const Optional<V>&) noexcept {
506 bool operator<=(const Optional<V>& a, None) noexcept {
507 return !a.hasValue();
510 bool operator>=(const Optional<V>&, None) noexcept {
514 bool operator>=(None, const Optional<V>& a) noexcept {
515 return !a.hasValue();
518 ///////////////////////////////////////////////////////////////////////////////
522 // Allow usage of Optional<T> in std::unordered_map and std::unordered_set
523 FOLLY_NAMESPACE_STD_BEGIN
525 struct hash<folly::Optional<T>> {
526 size_t operator()(folly::Optional<T> const& obj) const {
527 if (!obj.hasValue()) {
530 return hash<typename remove_const<T>::type>()(*obj);
533 FOLLY_NAMESPACE_STD_END
535 // Enable the use of folly::Optional with `co_await`
536 // Inspired by https://github.com/toby-allsopp/coroutine_monad
537 #if FOLLY_HAS_COROUTINES
538 #include <experimental/coroutine>
542 template <typename Value>
543 struct OptionalPromise;
545 template <typename Value>
546 struct OptionalPromiseReturn {
547 Optional<Value> storage_;
548 OptionalPromise<Value>* promise_;
549 /* implicit */ OptionalPromiseReturn(OptionalPromise<Value>& promise) noexcept
550 : promise_(&promise) {
551 promise.value_ = &storage_;
553 OptionalPromiseReturn(OptionalPromiseReturn&& that) noexcept
554 : OptionalPromiseReturn{*that.promise_} {}
555 ~OptionalPromiseReturn() {}
556 /* implicit */ operator Optional<Value>() & {
557 return std::move(storage_);
561 template <typename Value>
562 struct OptionalPromise {
563 Optional<Value>* value_ = nullptr;
564 OptionalPromise() = default;
565 OptionalPromise(OptionalPromise const&) = delete;
566 // This should work regardless of whether the compiler generates:
567 // folly::Optional<Value> retobj{ p.get_return_object(); } // MSVC
569 // auto retobj = p.get_return_object(); // clang
570 OptionalPromiseReturn<Value> get_return_object() noexcept {
573 std::experimental::suspend_never initial_suspend() const noexcept {
576 std::experimental::suspend_never final_suspend() const {
579 template <typename U>
580 void return_value(U&& u) {
581 *value_ = static_cast<U&&>(u);
583 void unhandled_exception() {
584 // Technically, throwing from unhandled_exception is underspecified:
585 // https://github.com/GorNishanov/CoroutineWording/issues/17
590 template <typename Value>
591 struct OptionalAwaitable {
593 bool await_ready() const noexcept {
594 return o_.hasValue();
596 Value await_resume() {
599 template <typename CoroHandle>
600 void await_suspend(CoroHandle h) const {
601 // make sure the coroutine returns an empty Optional:
602 h.promise().value_->clear();
603 // Abort the rest of the coroutine:
607 } // namespace detail
609 template <typename Value>
610 detail::OptionalAwaitable<Value>
611 /* implicit */ operator co_await(Optional<Value> o) {
612 return {std::move(o)};
616 // This makes std::optional<Value> useable as a coroutine return type..
617 FOLLY_NAMESPACE_STD_BEGIN
618 namespace experimental {
619 template <typename Value, typename... Args>
620 struct coroutine_traits<folly::Optional<Value>, Args...> {
621 using promise_type = folly::detail::OptionalPromise<Value>;
624 FOLLY_NAMESPACE_STD_END
625 #endif // FOLLY_HAS_COROUTINES