2 * Copyright 2016 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)) {
59 #include <type_traits>
64 namespace detail { struct NoneHelper {}; }
66 typedef int detail::NoneHelper::*None;
68 const None none = nullptr;
71 * gcc-4.7 warns about use of uninitialized memory around the use of storage_
72 * even though this is explicitly initialized at each point.
74 #if defined(__GNUC__) && !defined(__clang__)
75 # pragma GCC diagnostic push
76 # pragma GCC diagnostic ignored "-Wuninitialized"
77 # pragma GCC diagnostic ignored "-Wpragmas"
78 # pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
81 class OptionalEmptyException : public std::runtime_error {
83 OptionalEmptyException()
84 : std::runtime_error("Empty Optional cannot be unwrapped") {}
90 typedef Value value_type;
92 static_assert(!std::is_reference<Value>::value,
93 "Optional may not be used with reference types");
94 static_assert(!std::is_abstract<Value>::value,
95 "Optional may not be used with abstract types");
100 Optional(const Optional& src)
101 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
103 if (src.hasValue()) {
104 construct(src.value());
108 Optional(Optional&& src)
109 noexcept(std::is_nothrow_move_constructible<Value>::value) {
111 if (src.hasValue()) {
112 construct(std::move(src.value()));
117 /* implicit */ Optional(const None&) noexcept {
120 /* implicit */ Optional(Value&& newValue)
121 noexcept(std::is_nothrow_move_constructible<Value>::value) {
122 construct(std::move(newValue));
125 /* implicit */ Optional(const Value& newValue)
126 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
130 void assign(const None&) {
134 void assign(Optional&& src) {
136 if (src.hasValue()) {
137 assign(std::move(src.value()));
145 void assign(const Optional& src) {
146 if (src.hasValue()) {
153 void assign(Value&& newValue) {
155 storage_.value = std::move(newValue);
157 construct(std::move(newValue));
161 void assign(const Value& newValue) {
163 storage_.value = newValue;
170 Optional& operator=(Arg&& arg) {
171 assign(std::forward<Arg>(arg));
175 Optional& operator=(Optional &&other)
176 noexcept (std::is_nothrow_move_assignable<Value>::value) {
178 assign(std::move(other));
182 Optional& operator=(const Optional &other)
183 noexcept (std::is_nothrow_copy_assignable<Value>::value) {
189 template<class... Args>
190 void emplace(Args&&... args) {
192 construct(std::forward<Args>(args)...);
199 const Value& value() const& {
201 return storage_.value;
206 return storage_.value;
211 return std::move(storage_.value);
214 const Value* get_pointer() const& {
215 return storage_.hasValue ? &storage_.value : nullptr;
217 Value* get_pointer() & {
218 return storage_.hasValue ? &storage_.value : nullptr;
220 Value* get_pointer() && = delete;
222 bool hasValue() const { return storage_.hasValue; }
224 explicit operator bool() const {
228 const Value& operator*() const& { return value(); }
229 Value& operator*() & { return value(); }
230 Value operator*() && { return std::move(value()); }
232 const Value* operator->() const { return &value(); }
233 Value* operator->() { return &value(); }
235 // Return a copy of the value if set, or a given default if not.
237 Value value_or(U&& dflt) const& {
238 if (storage_.hasValue) {
239 return storage_.value;
242 return std::forward<U>(dflt);
246 Value value_or(U&& dflt) && {
247 if (storage_.hasValue) {
248 return std::move(storage_.value);
251 return std::forward<U>(dflt);
255 void require_value() const {
256 if (!storage_.hasValue) {
257 throw OptionalEmptyException();
261 template<class... Args>
262 void construct(Args&&... args) {
263 const void* ptr = &storage_.value;
264 // for supporting const types
265 new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
266 storage_.hasValue = true;
269 struct StorageTriviallyDestructible {
271 union { Value value; };
274 StorageTriviallyDestructible() : hasValue{false} {}
281 struct StorageNonTriviallyDestructible {
283 union { Value value; };
286 StorageNonTriviallyDestructible() : hasValue{false} {}
288 ~StorageNonTriviallyDestructible() {
301 typename std::conditional<std::is_trivially_destructible<Value>::value,
302 StorageTriviallyDestructible,
303 StorageNonTriviallyDestructible>::type;
308 #if defined(__GNUC__) && !defined(__clang__)
309 #pragma GCC diagnostic pop
313 const T* get_pointer(const Optional<T>& opt) {
314 return opt.get_pointer();
318 T* get_pointer(Optional<T>& opt) {
319 return opt.get_pointer();
323 void swap(Optional<T>& a, Optional<T>& b) {
324 if (a.hasValue() && b.hasValue()) {
327 swap(a.value(), b.value());
328 } else if (a.hasValue() || b.hasValue()) {
329 std::swap(a, b); // fall back to default implementation if they're mixed.
334 class Opt = Optional<typename std::decay<T>::type>>
335 Opt make_optional(T&& v) {
336 return Opt(std::forward<T>(v));
339 ///////////////////////////////////////////////////////////////////////////////
343 bool operator==(const Optional<V>& a, const V& b) {
344 return a.hasValue() && a.value() == b;
348 bool operator!=(const Optional<V>& a, const V& b) {
353 bool operator==(const V& a, const Optional<V>& b) {
354 return b.hasValue() && b.value() == a;
358 bool operator!=(const V& a, const Optional<V>& b) {
363 bool operator==(const Optional<V>& a, const Optional<V>& b) {
364 if (a.hasValue() != b.hasValue()) { return false; }
365 if (a.hasValue()) { return a.value() == b.value(); }
370 bool operator!=(const Optional<V>& a, const Optional<V>& b) {
375 bool operator< (const Optional<V>& a, const Optional<V>& b) {
376 if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
377 if (a.hasValue()) { return a.value() < b.value(); }
382 bool operator> (const Optional<V>& a, const Optional<V>& b) {
387 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
392 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
396 // Suppress comparability of Optional<T> with T, despite implicit conversion.
397 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
398 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
399 template<class V> bool operator>=(const Optional<V>&, const V& other) = delete;
400 template<class V> bool operator> (const Optional<V>&, const V& other) = delete;
401 template<class V> bool operator< (const V& other, const Optional<V>&) = delete;
402 template<class V> bool operator<=(const V& other, const Optional<V>&) = delete;
403 template<class V> bool operator>=(const V& other, const Optional<V>&) = delete;
404 template<class V> bool operator> (const V& other, const Optional<V>&) = delete;
406 ///////////////////////////////////////////////////////////////////////////////