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)) {
60 #include <type_traits>
63 #include <folly/Portability.h>
70 // Allow each translation unit to control its own -fexceptions setting.
71 // If exceptions are disabled, std::terminate() will be called instead of
72 // throwing OptionalEmptyException when the condition fails.
73 [[noreturn]] void throw_optional_empty_exception();
76 typedef int detail::NoneHelper::*None;
78 const None none = nullptr;
80 class OptionalEmptyException : public std::runtime_error {
82 OptionalEmptyException()
83 : std::runtime_error("Empty Optional cannot be unwrapped") {}
89 typedef Value value_type;
91 static_assert(!std::is_reference<Value>::value,
92 "Optional may not be used with reference types");
93 static_assert(!std::is_abstract<Value>::value,
94 "Optional may not be used with abstract types");
99 Optional(const Optional& src)
100 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
102 if (src.hasValue()) {
103 construct(src.value());
107 Optional(Optional&& src)
108 noexcept(std::is_nothrow_move_constructible<Value>::value) {
110 if (src.hasValue()) {
111 construct(std::move(src.value()));
116 /* implicit */ Optional(const None&) noexcept {
119 /* implicit */ Optional(Value&& newValue)
120 noexcept(std::is_nothrow_move_constructible<Value>::value) {
121 construct(std::move(newValue));
124 /* implicit */ Optional(const Value& newValue)
125 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
129 void assign(const None&) {
133 void assign(Optional&& src) {
135 if (src.hasValue()) {
136 assign(std::move(src.value()));
144 void assign(const Optional& src) {
145 if (src.hasValue()) {
152 void assign(Value&& newValue) {
154 storage_.value = std::move(newValue);
156 construct(std::move(newValue));
160 void assign(const Value& newValue) {
162 storage_.value = newValue;
169 Optional& operator=(Arg&& arg) {
170 assign(std::forward<Arg>(arg));
174 Optional& operator=(Optional &&other)
175 noexcept (std::is_nothrow_move_assignable<Value>::value) {
177 assign(std::move(other));
181 Optional& operator=(const Optional &other)
182 noexcept (std::is_nothrow_copy_assignable<Value>::value) {
188 template<class... Args>
189 void emplace(Args&&... args) {
191 construct(std::forward<Args>(args)...);
198 const Value& value() const& {
200 return storage_.value;
205 return storage_.value;
210 return std::move(storage_.value);
213 const Value&& value() const&& {
215 return std::move(storage_.value);
218 const Value* get_pointer() const& {
219 return storage_.hasValue ? &storage_.value : nullptr;
221 Value* get_pointer() & {
222 return storage_.hasValue ? &storage_.value : nullptr;
224 Value* get_pointer() && = delete;
226 bool hasValue() const { return storage_.hasValue; }
228 explicit operator bool() const {
232 const Value& operator*() const& { return value(); }
233 Value& operator*() & { return value(); }
234 const Value&& operator*() const&& { return std::move(value()); }
235 Value&& operator*() && { return std::move(value()); }
237 const Value* operator->() const { return &value(); }
238 Value* operator->() { return &value(); }
240 // Return a copy of the value if set, or a given default if not.
242 Value value_or(U&& dflt) const& {
243 if (storage_.hasValue) {
244 return storage_.value;
247 return std::forward<U>(dflt);
251 Value value_or(U&& dflt) && {
252 if (storage_.hasValue) {
253 return std::move(storage_.value);
256 return std::forward<U>(dflt);
260 void require_value() const {
261 if (!storage_.hasValue) {
262 detail::throw_optional_empty_exception();
266 template<class... Args>
267 void construct(Args&&... args) {
268 const void* ptr = &storage_.value;
269 // for supporting const types
270 new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
271 storage_.hasValue = true;
274 struct StorageTriviallyDestructible {
275 // The union trick allows to initialize the Optional's memory,
276 // so that compiler/tools don't complain about uninitialized memory,
277 // without actually calling Value's default constructor.
278 // The rest of the implementation enforces that hasValue/value are
283 bool paddingForHasValue_[1];
288 StorageTriviallyDestructible() : hasValue{false} {}
295 struct StorageNonTriviallyDestructible {
296 // See StorageTriviallyDestructible's union
300 bool paddingForHasValue_[1];
306 // These are both informational warnings, but they trigger rare enough
307 // that we've left them enabled.
308 FOLLY_MSVC_DISABLE_WARNING(4587) // constructor of .value is not called
309 FOLLY_MSVC_DISABLE_WARNING(4588) // destructor of .value is not called
310 StorageNonTriviallyDestructible() : hasValue{false} {}
311 ~StorageNonTriviallyDestructible() {
325 typename std::conditional<std::is_trivially_destructible<Value>::value,
326 StorageTriviallyDestructible,
327 StorageNonTriviallyDestructible>::type;
333 const T* get_pointer(const Optional<T>& opt) {
334 return opt.get_pointer();
338 T* get_pointer(Optional<T>& opt) {
339 return opt.get_pointer();
343 void swap(Optional<T>& a, Optional<T>& b) {
344 if (a.hasValue() && b.hasValue()) {
347 swap(a.value(), b.value());
348 } else if (a.hasValue() || b.hasValue()) {
349 std::swap(a, b); // fall back to default implementation if they're mixed.
354 class Opt = Optional<typename std::decay<T>::type>>
355 Opt make_optional(T&& v) {
356 return Opt(std::forward<T>(v));
359 ///////////////////////////////////////////////////////////////////////////////
363 bool operator==(const Optional<V>& a, const V& b) {
364 return a.hasValue() && a.value() == b;
368 bool operator!=(const Optional<V>& a, const V& b) {
373 bool operator==(const V& a, const Optional<V>& b) {
374 return b.hasValue() && b.value() == a;
378 bool operator!=(const V& a, const Optional<V>& b) {
383 bool operator==(const Optional<V>& a, const Optional<V>& b) {
384 if (a.hasValue() != b.hasValue()) { return false; }
385 if (a.hasValue()) { return a.value() == b.value(); }
390 bool operator!=(const Optional<V>& a, const Optional<V>& b) {
395 bool operator< (const Optional<V>& a, const Optional<V>& b) {
396 if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
397 if (a.hasValue()) { return a.value() < b.value(); }
402 bool operator> (const Optional<V>& a, const Optional<V>& b) {
407 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
412 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
416 // Suppress comparability of Optional<T> with T, despite implicit conversion.
417 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
418 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
419 template<class V> bool operator>=(const Optional<V>&, const V& other) = delete;
420 template<class V> bool operator> (const Optional<V>&, const V& other) = delete;
421 template<class V> bool operator< (const V& other, const Optional<V>&) = delete;
422 template<class V> bool operator<=(const V& other, const Optional<V>&) = delete;
423 template<class V> bool operator>=(const V& other, const Optional<V>&) = delete;
424 template<class V> bool operator> (const V& other, const Optional<V>&) = delete;
426 ///////////////////////////////////////////////////////////////////////////////
430 // Allow usage of Optional<T> in std::unordered_map and std::unordered_set
431 FOLLY_NAMESPACE_STD_BEGIN
433 struct hash<folly::Optional<T>> {
434 size_t operator()(folly::Optional<T> const& obj) const {
435 if (!obj.hasValue()) {
438 return hash<typename remove_const<T>::type>()(*obj);
441 FOLLY_NAMESPACE_STD_END