Disabling conversion with contained value for Optional
[folly.git] / folly / Optional.h
1 /*
2  * Copyright 2013 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
65 namespace folly {
66
67 namespace detail { struct NoneHelper {}; }
68
69 typedef int detail::NoneHelper::*None;
70
71 const None none = nullptr;
72
73 /**
74  * gcc-4.7 warns about use of uninitialized memory around the use of storage_
75  * even though this is explicitly initialized at each point.
76  */
77 #if defined(__GNUC__) && !defined(__clang__)
78 # pragma GCC diagnostic push
79 # pragma GCC diagnostic ignored "-Wuninitialized"
80 # pragma GCC diagnostic ignored "-Wpragmas"
81 # pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
82 #endif // __GNUC__
83
84 template<class Value>
85 class Optional {
86  public:
87   static_assert(!std::is_reference<Value>::value,
88                 "Optional may not be used with reference types");
89
90   Optional()
91     : hasValue_(false) {
92   }
93
94   Optional(const Optional& src) {
95     if (src.hasValue()) {
96       construct(src.value());
97     } else {
98       hasValue_ = false;
99     }
100   }
101
102   Optional(Optional&& src) {
103     if (src.hasValue()) {
104       construct(std::move(src.value()));
105       src.clear();
106     } else {
107       hasValue_ = false;
108     }
109   }
110
111   /* implicit */ Optional(const None&)
112     : hasValue_(false) {
113   }
114
115   /* implicit */ Optional(Value&& newValue) {
116     construct(std::move(newValue));
117   }
118
119   /* implicit */ Optional(const Value& newValue) {
120     construct(newValue);
121   }
122
123   ~Optional() {
124     clear();
125   }
126
127   void assign(const None&) {
128     clear();
129   }
130
131   void assign(Optional&& src) {
132     if (src.hasValue()) {
133       assign(std::move(src.value()));
134       src.clear();
135     } else {
136       clear();
137     }
138   }
139
140   void assign(const Optional& src) {
141     if (src.hasValue()) {
142       assign(src.value());
143     } else {
144       clear();
145     }
146   }
147
148   void assign(Value&& newValue) {
149     if (hasValue()) {
150       value_ = std::move(newValue);
151     } else {
152       construct(std::move(newValue));
153     }
154   }
155
156   void assign(const Value& newValue) {
157     if (hasValue()) {
158       value_ = newValue;
159     } else {
160       construct(newValue);
161     }
162   }
163
164   template<class Arg>
165   Optional& operator=(Arg&& arg) {
166     assign(std::forward<Arg>(arg));
167     return *this;
168   }
169
170   Optional& operator=(Optional &&other) {
171     assign(std::move(other));
172     return *this;
173   }
174
175   Optional& operator=(const Optional &other) {
176     assign(other);
177     return *this;
178   }
179
180   template<class... Args>
181   void emplace(Args&&... args) {
182     clear();
183     construct(std::forward<Args>(args)...);
184   }
185
186   void clear() {
187     if (hasValue()) {
188       hasValue_ = false;
189       value_.~Value();
190     }
191   }
192
193   const Value& value() const {
194     assert(hasValue());
195     return value_;
196   }
197
198   Value& value() {
199     assert(hasValue());
200     return value_;
201   }
202
203   bool hasValue() const { return hasValue_; }
204
205   explicit operator bool() const {
206     return hasValue();
207   }
208
209   const Value& operator*() const { return value(); }
210         Value& operator*()       { return value(); }
211
212   const Value* operator->() const { return &value(); }
213         Value* operator->()       { return &value(); }
214
215  private:
216   template<class... Args>
217   void construct(Args&&... args) {
218     const void* ptr = &value_;
219     // for supporting const types
220     new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
221     hasValue_ = true;
222   }
223
224   // uninitialized
225   union { Value value_; };
226   bool hasValue_;
227 };
228
229 #if defined(__GNUC__) && !defined(__clang__)
230 #pragma GCC diagnostic pop
231 #endif
232
233 template<class T>
234 const T* get_pointer(const Optional<T>& opt) {
235   return opt ? &opt.value() : nullptr;
236 }
237
238 template<class T>
239 T* get_pointer(Optional<T>& opt) {
240   return opt ? &opt.value() : nullptr;
241 }
242
243 template<class T>
244 void swap(Optional<T>& a, Optional<T>& b) {
245   if (a.hasValue() && b.hasValue()) {
246     // both full
247     using std::swap;
248     swap(a.value(), b.value());
249   } else if (a.hasValue() || b.hasValue()) {
250     std::swap(a, b); // fall back to default implementation if they're mixed.
251   }
252 }
253
254 template<class T,
255          class Opt = Optional<typename std::decay<T>::type>>
256 Opt make_optional(T&& v) {
257   return Opt(std::forward<T>(v));
258 }
259
260 template<class V>
261 bool operator< (const Optional<V>& a, const Optional<V>& b) {
262   if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
263   if (a.hasValue())                 { return a.value()    < b.value(); }
264   return false;
265 }
266
267 template<class V>
268 bool operator==(const Optional<V>& a, const Optional<V>& b) {
269   if (a.hasValue() != b.hasValue()) { return false; }
270   if (a.hasValue())                 { return a.value() == b.value(); }
271   return true;
272 }
273
274 template<class V>
275 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
276   return !(b < a);
277 }
278
279 template<class V>
280 bool operator!=(const Optional<V>& a, const Optional<V>& b) {
281   return !(b == a);
282 }
283
284 template<class V>
285 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
286   return !(a < b);
287 }
288
289 template<class V>
290 bool operator> (const Optional<V>& a, const Optional<V>& b) {
291   return b < a;
292 }
293
294 // To supress comparability of Optional<T> with T, despite implicit conversion.
295 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
296 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
297 template<class V> bool operator==(const Optional<V>&, const V& other) = delete;
298 template<class V> bool operator!=(const Optional<V>&, const V& other) = delete;
299 template<class V> bool operator>=(const Optional<V>&, const V& other) = delete;
300 template<class V> bool operator> (const Optional<V>&, const V& other) = delete;
301 template<class V> bool operator< (const V& other, const Optional<V>&) = delete;
302 template<class V> bool operator<=(const V& other, const Optional<V>&) = delete;
303 template<class V> bool operator==(const V& other, const Optional<V>&) = delete;
304 template<class V> bool operator!=(const V& other, const Optional<V>&) = delete;
305 template<class V> bool operator>=(const V& other, const Optional<V>&) = delete;
306 template<class V> bool operator> (const V& other, const Optional<V>&) = delete;
307
308 } // namespace folly
309
310 #endif//FOLLY_OPTIONAL_H_