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>
62 #include <folly/Portability.h>
66 namespace detail { struct NoneHelper {}; }
68 typedef int detail::NoneHelper::*None;
70 const None none = nullptr;
72 class OptionalEmptyException : public std::runtime_error {
74 OptionalEmptyException()
75 : std::runtime_error("Empty Optional cannot be unwrapped") {}
81 typedef Value value_type;
83 static_assert(!std::is_reference<Value>::value,
84 "Optional may not be used with reference types");
85 static_assert(!std::is_abstract<Value>::value,
86 "Optional may not be used with abstract types");
91 Optional(const Optional& src)
92 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
95 construct(src.value());
99 Optional(Optional&& src)
100 noexcept(std::is_nothrow_move_constructible<Value>::value) {
102 if (src.hasValue()) {
103 construct(std::move(src.value()));
108 /* implicit */ Optional(const None&) noexcept {
111 /* implicit */ Optional(Value&& newValue)
112 noexcept(std::is_nothrow_move_constructible<Value>::value) {
113 construct(std::move(newValue));
116 /* implicit */ Optional(const Value& newValue)
117 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
121 void assign(const None&) {
125 void assign(Optional&& src) {
127 if (src.hasValue()) {
128 assign(std::move(src.value()));
136 void assign(const Optional& src) {
137 if (src.hasValue()) {
144 void assign(Value&& newValue) {
146 storage_.value = std::move(newValue);
148 construct(std::move(newValue));
152 void assign(const Value& newValue) {
154 storage_.value = newValue;
161 Optional& operator=(Arg&& arg) {
162 assign(std::forward<Arg>(arg));
166 Optional& operator=(Optional &&other)
167 noexcept (std::is_nothrow_move_assignable<Value>::value) {
169 assign(std::move(other));
173 Optional& operator=(const Optional &other)
174 noexcept (std::is_nothrow_copy_assignable<Value>::value) {
180 template<class... Args>
181 void emplace(Args&&... args) {
183 construct(std::forward<Args>(args)...);
190 const Value& value() const& {
192 return storage_.value;
197 return storage_.value;
202 return std::move(storage_.value);
205 const Value&& value() const&& {
207 return std::move(storage_.value);
210 const Value* get_pointer() const& {
211 return storage_.hasValue ? &storage_.value : nullptr;
213 Value* get_pointer() & {
214 return storage_.hasValue ? &storage_.value : nullptr;
216 Value* get_pointer() && = delete;
218 bool hasValue() const { return storage_.hasValue; }
220 explicit operator bool() const {
224 const Value& operator*() const& { return value(); }
225 Value& operator*() & { return value(); }
226 const Value&& operator*() const&& { return std::move(value()); }
227 Value&& operator*() && { return std::move(value()); }
229 const Value* operator->() const { return &value(); }
230 Value* operator->() { return &value(); }
232 // Return a copy of the value if set, or a given default if not.
234 Value value_or(U&& dflt) const& {
235 if (storage_.hasValue) {
236 return storage_.value;
239 return std::forward<U>(dflt);
243 Value value_or(U&& dflt) && {
244 if (storage_.hasValue) {
245 return std::move(storage_.value);
248 return std::forward<U>(dflt);
252 void require_value() const {
253 if (!storage_.hasValue) {
254 throw OptionalEmptyException();
258 template<class... Args>
259 void construct(Args&&... args) {
260 const void* ptr = &storage_.value;
261 // for supporting const types
262 new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
263 storage_.hasValue = true;
266 struct StorageTriviallyDestructible {
267 // The union trick allows to initialize the Optional's memory,
268 // so that compiler/tools don't complain about unitialized memory,
269 // without actually calling Value's default constructor.
270 // The rest of the implementation enforces that hasValue/value are
275 bool paddingForHasValue_[1];
280 StorageTriviallyDestructible() : hasValue{false} {}
287 struct StorageNonTriviallyDestructible {
288 // See StorageTriviallyDestructible's union
292 bool paddingForHasValue_[1];
298 // These are both informational warnings, but they trigger rare enough
299 // that we've left them enabled.
300 FOLLY_MSVC_DISABLE_WARNING(4587) // constructor of .value is not called
301 FOLLY_MSVC_DISABLE_WARNING(4588) // destructor of .value is not called
302 StorageNonTriviallyDestructible() : hasValue{false} {}
303 ~StorageNonTriviallyDestructible() {
317 typename std::conditional<std::is_trivially_destructible<Value>::value,
318 StorageTriviallyDestructible,
319 StorageNonTriviallyDestructible>::type;
325 const T* get_pointer(const Optional<T>& opt) {
326 return opt.get_pointer();
330 T* get_pointer(Optional<T>& opt) {
331 return opt.get_pointer();
335 void swap(Optional<T>& a, Optional<T>& b) {
336 if (a.hasValue() && b.hasValue()) {
339 swap(a.value(), b.value());
340 } else if (a.hasValue() || b.hasValue()) {
341 std::swap(a, b); // fall back to default implementation if they're mixed.
346 class Opt = Optional<typename std::decay<T>::type>>
347 Opt make_optional(T&& v) {
348 return Opt(std::forward<T>(v));
351 ///////////////////////////////////////////////////////////////////////////////
355 bool operator==(const Optional<V>& a, const V& b) {
356 return a.hasValue() && a.value() == b;
360 bool operator!=(const Optional<V>& a, const V& b) {
365 bool operator==(const V& a, const Optional<V>& b) {
366 return b.hasValue() && b.value() == a;
370 bool operator!=(const V& a, const Optional<V>& b) {
375 bool operator==(const Optional<V>& a, const Optional<V>& b) {
376 if (a.hasValue() != b.hasValue()) { return false; }
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) {
388 if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
389 if (a.hasValue()) { return a.value() < b.value(); }
394 bool operator> (const Optional<V>& a, const Optional<V>& b) {
399 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
404 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
408 // Suppress comparability of Optional<T> with T, despite implicit conversion.
409 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
410 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
411 template<class V> bool operator>=(const Optional<V>&, const V& other) = delete;
412 template<class V> bool operator> (const Optional<V>&, const V& other) = delete;
413 template<class V> bool operator< (const V& other, const Optional<V>&) = delete;
414 template<class V> bool operator<=(const V& other, const Optional<V>&) = delete;
415 template<class V> bool operator>=(const V& other, const Optional<V>&) = delete;
416 template<class V> bool operator> (const V& other, const Optional<V>&) = delete;
418 ///////////////////////////////////////////////////////////////////////////////