Copyright 2014->2015
[folly.git] / folly / Optional.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #ifndef FOLLY_OPTIONAL_H_
18 #define FOLLY_OPTIONAL_H_
19
20 /*
21  * Optional - For conditional initialization of values, like boost::optional,
22  * but with support for move semantics and emplacement.  Reference type support
23  * has not been included due to limited use cases and potential confusion with
24  * semantics of assignment: Assigning to an optional reference could quite
25  * reasonably copy its value or redirect the reference.
26  *
27  * Optional can be useful when a variable might or might not be needed:
28  *
29  *  Optional<Logger> maybeLogger = ...;
30  *  if (maybeLogger) {
31  *    maybeLogger->log("hello");
32  *  }
33  *
34  * Optional enables a 'null' value for types which do not otherwise have
35  * nullability, especially useful for parameter passing:
36  *
37  * void testIterator(const unique_ptr<Iterator>& it,
38  *                   initializer_list<int> idsExpected,
39  *                   Optional<initializer_list<int>> ranksExpected = none) {
40  *   for (int i = 0; it->next(); ++i) {
41  *     EXPECT_EQ(it->doc().id(), idsExpected[i]);
42  *     if (ranksExpected) {
43  *       EXPECT_EQ(it->doc().rank(), (*ranksExpected)[i]);
44  *     }
45  *   }
46  * }
47  *
48  * Optional models OptionalPointee, so calling 'get_pointer(opt)' will return a
49  * pointer to nullptr if the 'opt' is empty, and a pointer to the value if it is
50  * not:
51  *
52  *  Optional<int> maybeInt = ...;
53  *  if (int* v = get_pointer(maybeInt)) {
54  *    cout << *v << endl;
55  *  }
56  */
57 #include <cassert>
58 #include <cstddef>
59 #include <type_traits>
60 #include <utility>
61
62 #include <boost/operators.hpp>
63
64 #include <folly/Portability.h>
65
66 namespace folly {
67
68 namespace detail { struct NoneHelper {}; }
69
70 typedef int detail::NoneHelper::*None;
71
72 const None none = nullptr;
73
74 /**
75  * gcc-4.7 warns about use of uninitialized memory around the use of storage_
76  * even though this is explicitly initialized at each point.
77  */
78 #if defined(__GNUC__) && !defined(__clang__)
79 # pragma GCC diagnostic push
80 # pragma GCC diagnostic ignored "-Wuninitialized"
81 # pragma GCC diagnostic ignored "-Wpragmas"
82 # pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
83 #endif // __GNUC__
84
85 template<class Value>
86 class Optional {
87  public:
88   static_assert(!std::is_reference<Value>::value,
89                 "Optional may not be used with reference types");
90
91   Optional()
92     : hasValue_(false) {
93   }
94
95   Optional(const Optional& src)
96     noexcept(std::is_nothrow_copy_constructible<Value>::value) {
97
98     if (src.hasValue()) {
99       construct(src.value());
100     } else {
101       hasValue_ = false;
102     }
103   }
104
105   Optional(Optional&& src)
106     noexcept(std::is_nothrow_move_constructible<Value>::value) {
107
108     if (src.hasValue()) {
109       construct(std::move(src.value()));
110       src.clear();
111     } else {
112       hasValue_ = false;
113     }
114   }
115
116   /* implicit */ Optional(const None&) noexcept
117     : hasValue_(false) {
118   }
119
120   /* implicit */ Optional(Value&& newValue)
121     noexcept(std::is_nothrow_move_constructible<Value>::value) {
122     construct(std::move(newValue));
123   }
124
125   /* implicit */ Optional(const Value& newValue)
126     noexcept(std::is_nothrow_copy_constructible<Value>::value) {
127     construct(newValue);
128   }
129
130   ~Optional() noexcept {
131     clear();
132   }
133
134   void assign(const None&) {
135     clear();
136   }
137
138   void assign(Optional&& src) {
139     if (this != &src) {
140       if (src.hasValue()) {
141         assign(std::move(src.value()));
142         src.clear();
143       } else {
144         clear();
145       }
146     }
147   }
148
149   void assign(const Optional& src) {
150     if (src.hasValue()) {
151       assign(src.value());
152     } else {
153       clear();
154     }
155   }
156
157   void assign(Value&& newValue) {
158     if (hasValue()) {
159       value_ = std::move(newValue);
160     } else {
161       construct(std::move(newValue));
162     }
163   }
164
165   void assign(const Value& newValue) {
166     if (hasValue()) {
167       value_ = newValue;
168     } else {
169       construct(newValue);
170     }
171   }
172
173   template<class Arg>
174   Optional& operator=(Arg&& arg) {
175     assign(std::forward<Arg>(arg));
176     return *this;
177   }
178
179   Optional& operator=(Optional &&other)
180     noexcept (std::is_nothrow_move_assignable<Value>::value) {
181
182     assign(std::move(other));
183     return *this;
184   }
185
186   Optional& operator=(const Optional &other)
187     noexcept (std::is_nothrow_copy_assignable<Value>::value) {
188
189     assign(other);
190     return *this;
191   }
192
193   template<class... Args>
194   void emplace(Args&&... args) {
195     clear();
196     construct(std::forward<Args>(args)...);
197   }
198
199   void clear() {
200     if (hasValue()) {
201       hasValue_ = false;
202       value_.~Value();
203     }
204   }
205
206   const Value& value() const {
207     assert(hasValue());
208     return value_;
209   }
210
211   Value& value() {
212     assert(hasValue());
213     return value_;
214   }
215
216   bool hasValue() const { return hasValue_; }
217
218   explicit operator bool() const {
219     return hasValue();
220   }
221
222   const Value& operator*() const { return value(); }
223         Value& operator*()       { return value(); }
224
225   const Value* operator->() const { return &value(); }
226         Value* operator->()       { return &value(); }
227
228   // Return a copy of the value if set, or a given default if not.
229   template <class U>
230   Value value_or(U&& dflt) const& {
231     return hasValue_ ? value_ : std::forward<U>(dflt);
232   }
233
234   template <class U>
235   Value value_or(U&& dflt) && {
236     return hasValue_ ? std::move(value_) : std::forward<U>(dflt);
237   }
238
239  private:
240   template<class... Args>
241   void construct(Args&&... args) {
242     const void* ptr = &value_;
243     // for supporting const types
244     new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
245     hasValue_ = true;
246   }
247
248   // uninitialized
249   union { Value value_; };
250   bool hasValue_;
251 };
252
253 #if defined(__GNUC__) && !defined(__clang__)
254 #pragma GCC diagnostic pop
255 #endif
256
257 template<class T>
258 const T* get_pointer(const Optional<T>& opt) {
259   return opt ? &opt.value() : nullptr;
260 }
261
262 template<class T>
263 T* get_pointer(Optional<T>& opt) {
264   return opt ? &opt.value() : nullptr;
265 }
266
267 template<class T>
268 void swap(Optional<T>& a, Optional<T>& b) {
269   if (a.hasValue() && b.hasValue()) {
270     // both full
271     using std::swap;
272     swap(a.value(), b.value());
273   } else if (a.hasValue() || b.hasValue()) {
274     std::swap(a, b); // fall back to default implementation if they're mixed.
275   }
276 }
277
278 template<class T,
279          class Opt = Optional<typename std::decay<T>::type>>
280 Opt make_optional(T&& v) {
281   return Opt(std::forward<T>(v));
282 }
283
284 ///////////////////////////////////////////////////////////////////////////////
285 // Comparisons.
286
287 template<class V>
288 bool operator==(const Optional<V>& a, const V& b) {
289   return a.hasValue() && a.value() == b;
290 }
291
292 template<class V>
293 bool operator!=(const Optional<V>& a, const V& b) {
294   return !(a == b);
295 }
296
297 template<class V>
298 bool operator==(const V& a, const Optional<V>& b) {
299   return b.hasValue() && b.value() == a;
300 }
301
302 template<class V>
303 bool operator!=(const V& a, const Optional<V>& b) {
304   return !(a == b);
305 }
306
307 template<class V>
308 bool operator==(const Optional<V>& a, const Optional<V>& b) {
309   if (a.hasValue() != b.hasValue()) { return false; }
310   if (a.hasValue())                 { return a.value() == b.value(); }
311   return true;
312 }
313
314 template<class V>
315 bool operator!=(const Optional<V>& a, const Optional<V>& b) {
316   return !(a == b);
317 }
318
319 template<class V>
320 bool operator< (const Optional<V>& a, const Optional<V>& b) {
321   if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
322   if (a.hasValue())                 { return a.value()    < b.value(); }
323   return false;
324 }
325
326 template<class V>
327 bool operator> (const Optional<V>& a, const Optional<V>& b) {
328   return b < a;
329 }
330
331 template<class V>
332 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
333   return !(b < a);
334 }
335
336 template<class V>
337 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
338   return !(a < b);
339 }
340
341 // Suppress comparability of Optional<T> with T, despite implicit conversion.
342 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
343 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
344 template<class V> bool operator>=(const Optional<V>&, const V& other) = delete;
345 template<class V> bool operator> (const Optional<V>&, const V& other) = delete;
346 template<class V> bool operator< (const V& other, const Optional<V>&) = delete;
347 template<class V> bool operator<=(const V& other, const Optional<V>&) = delete;
348 template<class V> bool operator>=(const V& other, const Optional<V>&) = delete;
349 template<class V> bool operator> (const V& other, const Optional<V>&) = delete;
350
351 ///////////////////////////////////////////////////////////////////////////////
352
353 } // namespace folly
354
355 #endif // FOLLY_OPTIONAL_H_