Check for self-assignment in move assignment
[folly.git] / folly / Optional.h
1 /*
2  * Copyright 2014 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 <utility>
58 #include <cassert>
59 #include <cstddef>
60 #include <type_traits>
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  private:
229   template<class... Args>
230   void construct(Args&&... args) {
231     const void* ptr = &value_;
232     // for supporting const types
233     new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
234     hasValue_ = true;
235   }
236
237   // uninitialized
238   union { Value value_; };
239   bool hasValue_;
240 };
241
242 #if defined(__GNUC__) && !defined(__clang__)
243 #pragma GCC diagnostic pop
244 #endif
245
246 template<class T>
247 const T* get_pointer(const Optional<T>& opt) {
248   return opt ? &opt.value() : nullptr;
249 }
250
251 template<class T>
252 T* get_pointer(Optional<T>& opt) {
253   return opt ? &opt.value() : nullptr;
254 }
255
256 template<class T>
257 void swap(Optional<T>& a, Optional<T>& b) {
258   if (a.hasValue() && b.hasValue()) {
259     // both full
260     using std::swap;
261     swap(a.value(), b.value());
262   } else if (a.hasValue() || b.hasValue()) {
263     std::swap(a, b); // fall back to default implementation if they're mixed.
264   }
265 }
266
267 template<class T,
268          class Opt = Optional<typename std::decay<T>::type>>
269 Opt make_optional(T&& v) {
270   return Opt(std::forward<T>(v));
271 }
272
273 template<class V>
274 bool operator< (const Optional<V>& a, const Optional<V>& b) {
275   if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
276   if (a.hasValue())                 { return a.value()    < b.value(); }
277   return false;
278 }
279
280 template<class V>
281 bool operator==(const Optional<V>& a, const Optional<V>& b) {
282   if (a.hasValue() != b.hasValue()) { return false; }
283   if (a.hasValue())                 { return a.value() == b.value(); }
284   return true;
285 }
286
287 template<class V>
288 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
289   return !(b < a);
290 }
291
292 template<class V>
293 bool operator!=(const Optional<V>& a, const Optional<V>& b) {
294   return !(b == a);
295 }
296
297 template<class V>
298 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
299   return !(a < b);
300 }
301
302 template<class V>
303 bool operator> (const Optional<V>& a, const Optional<V>& b) {
304   return b < a;
305 }
306
307 // To supress comparability of Optional<T> with T, despite implicit conversion.
308 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
309 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
310 template<class V> bool operator==(const Optional<V>&, const V& other) = delete;
311 template<class V> bool operator!=(const Optional<V>&, const V& other) = delete;
312 template<class V> bool operator>=(const Optional<V>&, const V& other) = delete;
313 template<class V> bool operator> (const Optional<V>&, const V& other) = delete;
314 template<class V> bool operator< (const V& other, const Optional<V>&) = delete;
315 template<class V> bool operator<=(const V& other, const Optional<V>&) = delete;
316 template<class V> bool operator==(const V& other, const Optional<V>&) = delete;
317 template<class V> bool operator!=(const V& other, const Optional<V>&) = delete;
318 template<class V> bool operator>=(const V& other, const Optional<V>&) = delete;
319 template<class V> bool operator> (const V& other, const Optional<V>&) = delete;
320
321 } // namespace folly
322
323 #endif//FOLLY_OPTIONAL_H_