/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once /* * Optional - For conditional initialization of values, like boost::optional, * but with support for move semantics and emplacement. Reference type support * has not been included due to limited use cases and potential confusion with * semantics of assignment: Assigning to an optional reference could quite * reasonably copy its value or redirect the reference. * * Optional can be useful when a variable might or might not be needed: * * Optional maybeLogger = ...; * if (maybeLogger) { * maybeLogger->log("hello"); * } * * Optional enables a 'null' value for types which do not otherwise have * nullability, especially useful for parameter passing: * * void testIterator(const unique_ptr& it, * initializer_list idsExpected, * Optional> ranksExpected = none) { * for (int i = 0; it->next(); ++i) { * EXPECT_EQ(it->doc().id(), idsExpected[i]); * if (ranksExpected) { * EXPECT_EQ(it->doc().rank(), (*ranksExpected)[i]); * } * } * } * * Optional models OptionalPointee, so calling 'get_pointer(opt)' will return a * pointer to nullptr if the 'opt' is empty, and a pointer to the value if it is * not: * * Optional maybeInt = ...; * if (int* v = get_pointer(maybeInt)) { * cout << *v << endl; * } */ #include #include #include #include #include #include #include #include #include #include namespace folly { template class Optional; namespace detail { template struct OptionalPromiseReturn; } // namespace detail struct None { enum class _secret { _token }; /** * No default constructor to support both `op = {}` and `op = none` * as syntax for clearing an Optional, just like std::nullopt_t. */ explicit constexpr None(_secret) {} }; constexpr None none{None::_secret::_token}; class FOLLY_EXPORT OptionalEmptyException : public std::runtime_error { public: OptionalEmptyException() : std::runtime_error("Empty Optional cannot be unwrapped") {} }; template class Optional { public: typedef Value value_type; static_assert( !std::is_reference::value, "Optional may not be used with reference types"); static_assert( !std::is_abstract::value, "Optional may not be used with abstract types"); constexpr Optional() noexcept {} Optional(const Optional& src) noexcept( std::is_nothrow_copy_constructible::value) { if (src.hasValue()) { construct(src.value()); } } Optional(Optional&& src) noexcept( std::is_nothrow_move_constructible::value) { if (src.hasValue()) { construct(std::move(src.value())); src.clear(); } } constexpr /* implicit */ Optional(const None&) noexcept {} constexpr /* implicit */ Optional(Value&& newValue) noexcept( std::is_nothrow_move_constructible::value) { construct(std::move(newValue)); } constexpr /* implicit */ Optional(const Value& newValue) noexcept( std::is_nothrow_copy_constructible::value) { construct(newValue); } template constexpr explicit Optional(in_place_t, Args&&... args) noexcept( std::is_nothrow_constructible::value) : Optional{PrivateConstructor{}, std::forward(args)...} {} template constexpr explicit Optional( in_place_t, std::initializer_list il, Args&&... args) noexcept(std:: is_nothrow_constructible< Value, std::initializer_list, Args...>::value) : Optional{PrivateConstructor{}, il, std::forward(args)...} {} // Used only when an Optional is used with coroutines on MSVC /* implicit */ Optional(const detail::OptionalPromiseReturn& p) : Optional{} { p.promise_->value_ = this; } void assign(const None&) { clear(); } void assign(Optional&& src) { if (this != &src) { if (src.hasValue()) { assign(std::move(src.value())); src.clear(); } else { clear(); } } } void assign(const Optional& src) { if (src.hasValue()) { assign(src.value()); } else { clear(); } } void assign(Value&& newValue) { if (hasValue()) { storage_.value = std::move(newValue); } else { construct(std::move(newValue)); } } void assign(const Value& newValue) { if (hasValue()) { storage_.value = newValue; } else { construct(newValue); } } Optional& operator=(None) noexcept { reset(); return *this; } template Optional& operator=(Arg&& arg) { assign(std::forward(arg)); return *this; } Optional& operator=(Optional&& other) noexcept( std::is_nothrow_move_assignable::value) { assign(std::move(other)); return *this; } Optional& operator=(const Optional& other) noexcept( std::is_nothrow_copy_assignable::value) { assign(other); return *this; } template Value& emplace(Args&&... args) { clear(); construct(std::forward(args)...); return value(); } template typename std::enable_if< std::is_constructible&, Args&&...>::value, Value&>::type emplace(std::initializer_list ilist, Args&&... args) { clear(); construct(ilist, std::forward(args)...); return value(); } void reset() noexcept { storage_.clear(); } void clear() noexcept { reset(); } void swap(Optional& that) noexcept(IsNothrowSwappable::value) { if (hasValue() && that.hasValue()) { using std::swap; swap(value(), that.value()); } else if (hasValue()) { that.emplace(std::move(value())); reset(); } else if (that.hasValue()) { emplace(std::move(that.value())); that.reset(); } } constexpr const Value& value() const& { require_value(); return storage_.value; } constexpr Value& value() & { require_value(); return storage_.value; } constexpr Value&& value() && { require_value(); return std::move(storage_.value); } constexpr const Value&& value() const&& { require_value(); return std::move(storage_.value); } const Value* get_pointer() const& { return storage_.hasValue ? &storage_.value : nullptr; } Value* get_pointer() & { return storage_.hasValue ? &storage_.value : nullptr; } Value* get_pointer() && = delete; constexpr bool has_value() const noexcept { return storage_.hasValue; } constexpr bool hasValue() const noexcept { return has_value(); } constexpr explicit operator bool() const noexcept { return has_value(); } constexpr const Value& operator*() const& { return value(); } constexpr Value& operator*() & { return value(); } constexpr const Value&& operator*() const&& { return std::move(value()); } constexpr Value&& operator*() && { return std::move(value()); } constexpr const Value* operator->() const { return &value(); } constexpr Value* operator->() { return &value(); } // Return a copy of the value if set, or a given default if not. template constexpr Value value_or(U&& dflt) const& { if (storage_.hasValue) { return storage_.value; } return std::forward(dflt); } template constexpr Value value_or(U&& dflt) && { if (storage_.hasValue) { return std::move(storage_.value); } return std::forward(dflt); } private: template friend constexpr Optional> make_optional(T&&); template friend constexpr Optional make_optional(Args&&... args); template friend constexpr Optional make_optional(std::initializer_list, As&&...); /** * Construct the optional in place, this is duplicated as a non-explicit * constructor to allow returning values that are non-movable from * make_optional using list initialization. * * Until C++17, at which point this will become unnecessary because of * specified prvalue elision. */ struct PrivateConstructor { explicit PrivateConstructor() = default; }; template constexpr Optional(PrivateConstructor, Args&&... args) noexcept( std::is_constructible::value) { construct(std::forward(args)...); } void require_value() const { if (!storage_.hasValue) { throw_exception(); } } template void construct(Args&&... args) { const void* ptr = &storage_.value; // For supporting const types. new (const_cast(ptr)) Value(std::forward(args)...); storage_.hasValue = true; } struct StorageTriviallyDestructible { union { char emptyState; Value value; }; bool hasValue; constexpr StorageTriviallyDestructible() : emptyState('\0'), hasValue{false} {} void clear() { hasValue = false; } }; struct StorageNonTriviallyDestructible { union { char emptyState; Value value; }; bool hasValue; StorageNonTriviallyDestructible() : hasValue{false} {} ~StorageNonTriviallyDestructible() { clear(); } void clear() { if (hasValue) { hasValue = false; value.~Value(); } } }; using Storage = typename std::conditional< std::is_trivially_destructible::value, StorageTriviallyDestructible, StorageNonTriviallyDestructible>::type; Storage storage_; }; template const T* get_pointer(const Optional& opt) { return opt.get_pointer(); } template T* get_pointer(Optional& opt) { return opt.get_pointer(); } template void swap(Optional& a, Optional& b) noexcept(noexcept(a.swap(b))) { a.swap(b); } template constexpr Optional> make_optional(T&& v) { using PrivateConstructor = typename folly::Optional>::PrivateConstructor; return {PrivateConstructor{}, std::forward(v)}; } template constexpr folly::Optional make_optional(Args&&... args) { using PrivateConstructor = typename folly::Optional::PrivateConstructor; return {PrivateConstructor{}, std::forward(args)...}; } template constexpr folly::Optional make_optional( std::initializer_list il, Args&&... args) { using PrivateConstructor = typename folly::Optional::PrivateConstructor; return {PrivateConstructor{}, il, std::forward(args)...}; } /////////////////////////////////////////////////////////////////////////////// // Comparisons. template constexpr bool operator==(const Optional& a, const V& b) { return a.hasValue() && a.value() == b; } template constexpr bool operator!=(const Optional& a, const V& b) { return !(a == b); } template constexpr bool operator==(const U& a, const Optional& b) { return b.hasValue() && b.value() == a; } template constexpr bool operator!=(const U& a, const Optional& b) { return !(a == b); } template constexpr bool operator==(const Optional& a, const Optional& b) { if (a.hasValue() != b.hasValue()) { return false; } if (a.hasValue()) { return a.value() == b.value(); } return true; } template constexpr bool operator!=(const Optional& a, const Optional& b) { return !(a == b); } template constexpr bool operator<(const Optional& a, const Optional& b) { if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); } if (a.hasValue()) { return a.value() < b.value(); } return false; } template constexpr bool operator>(const Optional& a, const Optional& b) { return b < a; } template constexpr bool operator<=(const Optional& a, const Optional& b) { return !(b < a); } template constexpr bool operator>=(const Optional& a, const Optional& b) { return !(a < b); } // Suppress comparability of Optional with T, despite implicit conversion. template bool operator<(const Optional&, const V& other) = delete; template bool operator<=(const Optional&, const V& other) = delete; template bool operator>=(const Optional&, const V& other) = delete; template bool operator>(const Optional&, const V& other) = delete; template bool operator<(const V& other, const Optional&) = delete; template bool operator<=(const V& other, const Optional&) = delete; template bool operator>=(const V& other, const Optional&) = delete; template bool operator>(const V& other, const Optional&) = delete; // Comparisons with none template constexpr bool operator==(const Optional& a, None) noexcept { return !a.hasValue(); } template constexpr bool operator==(None, const Optional& a) noexcept { return !a.hasValue(); } template constexpr bool operator<(const Optional&, None) noexcept { return false; } template constexpr bool operator<(None, const Optional& a) noexcept { return a.hasValue(); } template constexpr bool operator>(const Optional& a, None) noexcept { return a.hasValue(); } template constexpr bool operator>(None, const Optional&) noexcept { return false; } template constexpr bool operator<=(None, const Optional&) noexcept { return true; } template constexpr bool operator<=(const Optional& a, None) noexcept { return !a.hasValue(); } template constexpr bool operator>=(const Optional&, None) noexcept { return true; } template constexpr bool operator>=(None, const Optional& a) noexcept { return !a.hasValue(); } /////////////////////////////////////////////////////////////////////////////// } // namespace folly // Allow usage of Optional in std::unordered_map and std::unordered_set FOLLY_NAMESPACE_STD_BEGIN template struct hash> { size_t operator()(folly::Optional const& obj) const { if (!obj.hasValue()) { return 0; } return hash::type>()(*obj); } }; FOLLY_NAMESPACE_STD_END // Enable the use of folly::Optional with `co_await` // Inspired by https://github.com/toby-allsopp/coroutine_monad #if FOLLY_HAS_COROUTINES #include namespace folly { namespace detail { template struct OptionalPromise; template struct OptionalPromiseReturn { Optional storage_; OptionalPromise* promise_; /* implicit */ OptionalPromiseReturn(OptionalPromise& promise) noexcept : promise_(&promise) { promise.value_ = &storage_; } OptionalPromiseReturn(OptionalPromiseReturn&& that) noexcept : OptionalPromiseReturn{*that.promise_} {} ~OptionalPromiseReturn() {} /* implicit */ operator Optional() & { return std::move(storage_); } }; template struct OptionalPromise { Optional* value_ = nullptr; OptionalPromise() = default; OptionalPromise(OptionalPromise const&) = delete; // This should work regardless of whether the compiler generates: // folly::Optional retobj{ p.get_return_object(); } // MSVC // or: // auto retobj = p.get_return_object(); // clang OptionalPromiseReturn get_return_object() noexcept { return *this; } std::experimental::suspend_never initial_suspend() const noexcept { return {}; } std::experimental::suspend_never final_suspend() const { return {}; } template void return_value(U&& u) { *value_ = static_cast(u); } void unhandled_exception() { // Technically, throwing from unhandled_exception is underspecified: // https://github.com/GorNishanov/CoroutineWording/issues/17 throw; } }; template struct OptionalAwaitable { Optional o_; bool await_ready() const noexcept { return o_.hasValue(); } Value await_resume() { return std::move(o_.value()); } // Explicitly only allow suspension into an OptionalPromise template void await_suspend( std::experimental::coroutine_handle> h) const { // Abort the rest of the coroutine. resume() is not going to be called h.destroy(); } }; } // namespace detail template detail::OptionalAwaitable /* implicit */ operator co_await(Optional o) { return {std::move(o)}; } } // namespace folly // This makes folly::Optional useable as a coroutine return type.. namespace std { namespace experimental { template struct coroutine_traits, Args...> { using promise_type = folly::detail::OptionalPromise; }; } // namespace experimental } // namespace std #endif // FOLLY_HAS_COROUTINES