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>
67 namespace detail { struct NoneHelper {}; }
69 typedef int detail::NoneHelper::*None;
71 const None none = nullptr;
73 class OptionalEmptyException : public std::runtime_error {
75 OptionalEmptyException()
76 : std::runtime_error("Empty Optional cannot be unwrapped") {}
82 typedef Value value_type;
84 static_assert(!std::is_reference<Value>::value,
85 "Optional may not be used with reference types");
86 static_assert(!std::is_abstract<Value>::value,
87 "Optional may not be used with abstract types");
92 Optional(const Optional& src)
93 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
96 construct(src.value());
100 Optional(Optional&& src)
101 noexcept(std::is_nothrow_move_constructible<Value>::value) {
103 if (src.hasValue()) {
104 construct(std::move(src.value()));
109 /* implicit */ Optional(const None&) noexcept {
112 /* implicit */ Optional(Value&& newValue)
113 noexcept(std::is_nothrow_move_constructible<Value>::value) {
114 construct(std::move(newValue));
117 /* implicit */ Optional(const Value& newValue)
118 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
122 void assign(const None&) {
126 void assign(Optional&& src) {
128 if (src.hasValue()) {
129 assign(std::move(src.value()));
137 void assign(const Optional& src) {
138 if (src.hasValue()) {
145 void assign(Value&& newValue) {
147 storage_.value = std::move(newValue);
149 construct(std::move(newValue));
153 void assign(const Value& newValue) {
155 storage_.value = newValue;
162 Optional& operator=(Arg&& arg) {
163 assign(std::forward<Arg>(arg));
167 Optional& operator=(Optional &&other)
168 noexcept (std::is_nothrow_move_assignable<Value>::value) {
170 assign(std::move(other));
174 Optional& operator=(const Optional &other)
175 noexcept (std::is_nothrow_copy_assignable<Value>::value) {
181 template<class... Args>
182 void emplace(Args&&... args) {
184 construct(std::forward<Args>(args)...);
191 const Value& value() const& {
193 return storage_.value;
198 return storage_.value;
203 return std::move(storage_.value);
206 const Value&& value() const&& {
208 return std::move(storage_.value);
211 const Value* get_pointer() const& {
212 return storage_.hasValue ? &storage_.value : nullptr;
214 Value* get_pointer() & {
215 return storage_.hasValue ? &storage_.value : nullptr;
217 Value* get_pointer() && = delete;
219 bool hasValue() const { return storage_.hasValue; }
221 explicit operator bool() const {
225 const Value& operator*() const& { return value(); }
226 Value& operator*() & { return value(); }
227 const Value&& operator*() const&& { return std::move(value()); }
228 Value&& operator*() && { return std::move(value()); }
230 const Value* operator->() const { return &value(); }
231 Value* operator->() { return &value(); }
233 // Return a copy of the value if set, or a given default if not.
235 Value value_or(U&& dflt) const& {
236 if (storage_.hasValue) {
237 return storage_.value;
240 return std::forward<U>(dflt);
244 Value value_or(U&& dflt) && {
245 if (storage_.hasValue) {
246 return std::move(storage_.value);
249 return std::forward<U>(dflt);
253 void require_value() const {
254 if (!storage_.hasValue) {
255 throw OptionalEmptyException();
259 template<class... Args>
260 void construct(Args&&... args) {
261 const void* ptr = &storage_.value;
262 // for supporting const types
263 new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
264 storage_.hasValue = true;
267 struct StorageTriviallyDestructible {
268 // The union trick allows to initialize the Optional's memory,
269 // so that compiler/tools don't complain about uninitialized memory,
270 // without actually calling Value's default constructor.
271 // The rest of the implementation enforces that hasValue/value are
276 bool paddingForHasValue_[1];
281 StorageTriviallyDestructible() : hasValue{false} {}
288 struct StorageNonTriviallyDestructible {
289 // See StorageTriviallyDestructible's union
293 bool paddingForHasValue_[1];
299 // These are both informational warnings, but they trigger rare enough
300 // that we've left them enabled.
301 FOLLY_MSVC_DISABLE_WARNING(4587) // constructor of .value is not called
302 FOLLY_MSVC_DISABLE_WARNING(4588) // destructor of .value is not called
303 StorageNonTriviallyDestructible() : hasValue{false} {}
304 ~StorageNonTriviallyDestructible() {
318 typename std::conditional<std::is_trivially_destructible<Value>::value,
319 StorageTriviallyDestructible,
320 StorageNonTriviallyDestructible>::type;
326 const T* get_pointer(const Optional<T>& opt) {
327 return opt.get_pointer();
331 T* get_pointer(Optional<T>& opt) {
332 return opt.get_pointer();
336 void swap(Optional<T>& a, Optional<T>& b) {
337 if (a.hasValue() && b.hasValue()) {
340 swap(a.value(), b.value());
341 } else if (a.hasValue() || b.hasValue()) {
342 std::swap(a, b); // fall back to default implementation if they're mixed.
347 class Opt = Optional<typename std::decay<T>::type>>
348 Opt make_optional(T&& v) {
349 return Opt(std::forward<T>(v));
352 ///////////////////////////////////////////////////////////////////////////////
356 bool operator==(const Optional<V>& a, const V& b) {
357 return a.hasValue() && a.value() == b;
361 bool operator!=(const Optional<V>& a, const V& b) {
366 bool operator==(const V& a, const Optional<V>& b) {
367 return b.hasValue() && b.value() == a;
371 bool operator!=(const V& a, const Optional<V>& b) {
376 bool operator==(const Optional<V>& a, const Optional<V>& b) {
377 if (a.hasValue() != b.hasValue()) { return false; }
378 if (a.hasValue()) { return a.value() == b.value(); }
383 bool operator!=(const Optional<V>& a, const Optional<V>& b) {
388 bool operator< (const Optional<V>& a, const Optional<V>& b) {
389 if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
390 if (a.hasValue()) { return a.value() < b.value(); }
395 bool operator> (const Optional<V>& a, const Optional<V>& b) {
400 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
405 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
409 // Suppress comparability of Optional<T> with T, despite implicit conversion.
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 Optional<V>&, const V& other) = 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;
417 template<class V> bool operator> (const V& other, const Optional<V>&) = delete;
419 ///////////////////////////////////////////////////////////////////////////////
423 // Allow usage of Optional<T> in std::unordered_map and std::unordered_set
424 FOLLY_NAMESPACE_STD_BEGIN
426 struct hash<folly::Optional<T>> {
427 size_t operator()(folly::Optional<T> const& obj) const {
428 if (!obj.hasValue()) {
431 return hash<typename remove_const<T>::type>()(*obj);
434 FOLLY_NAMESPACE_STD_END