folly: gen: pmap: parallel version of map
[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
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     noexcept(std::is_nothrow_copy_constructible<Value>::value) {
96
97     if (src.hasValue()) {
98       construct(src.value());
99     } else {
100       hasValue_ = false;
101     }
102   }
103
104   Optional(Optional&& src)
105     noexcept(std::is_nothrow_move_constructible<Value>::value) {
106
107     if (src.hasValue()) {
108       construct(std::move(src.value()));
109       src.clear();
110     } else {
111       hasValue_ = false;
112     }
113   }
114
115   /* implicit */ Optional(const None&) noexcept
116     : hasValue_(false) {
117   }
118
119   /* implicit */ Optional(Value&& newValue)
120     noexcept(std::is_nothrow_move_constructible<Value>::value) {
121     construct(std::move(newValue));
122   }
123
124   /* implicit */ Optional(const Value& newValue)
125     noexcept(std::is_nothrow_copy_constructible<Value>::value) {
126     construct(newValue);
127   }
128
129   ~Optional() noexcept {
130     clear();
131   }
132
133   void assign(const None&) {
134     clear();
135   }
136
137   void assign(Optional&& src) {
138     if (src.hasValue()) {
139       assign(std::move(src.value()));
140       src.clear();
141     } else {
142       clear();
143     }
144   }
145
146   void assign(const Optional& src) {
147     if (src.hasValue()) {
148       assign(src.value());
149     } else {
150       clear();
151     }
152   }
153
154   void assign(Value&& newValue) {
155     if (hasValue()) {
156       value_ = std::move(newValue);
157     } else {
158       construct(std::move(newValue));
159     }
160   }
161
162   void assign(const Value& newValue) {
163     if (hasValue()) {
164       value_ = newValue;
165     } else {
166       construct(newValue);
167     }
168   }
169
170   template<class Arg>
171   Optional& operator=(Arg&& arg) {
172     assign(std::forward<Arg>(arg));
173     return *this;
174   }
175
176   Optional& operator=(Optional &&other)
177     noexcept (std::is_nothrow_move_assignable<Value>::value) {
178
179     assign(std::move(other));
180     return *this;
181   }
182
183   Optional& operator=(const Optional &other)
184     noexcept (std::is_nothrow_copy_assignable<Value>::value) {
185
186     assign(other);
187     return *this;
188   }
189
190   template<class... Args>
191   void emplace(Args&&... args) {
192     clear();
193     construct(std::forward<Args>(args)...);
194   }
195
196   void clear() {
197     if (hasValue()) {
198       hasValue_ = false;
199       value_.~Value();
200     }
201   }
202
203   const Value& value() const {
204     assert(hasValue());
205     return value_;
206   }
207
208   Value& value() {
209     assert(hasValue());
210     return value_;
211   }
212
213   bool hasValue() const { return hasValue_; }
214
215   explicit operator bool() const {
216     return hasValue();
217   }
218
219   const Value& operator*() const { return value(); }
220         Value& operator*()       { return value(); }
221
222   const Value* operator->() const { return &value(); }
223         Value* operator->()       { return &value(); }
224
225  private:
226   template<class... Args>
227   void construct(Args&&... args) {
228     const void* ptr = &value_;
229     // for supporting const types
230     new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
231     hasValue_ = true;
232   }
233
234   // uninitialized
235   union { Value value_; };
236   bool hasValue_;
237 };
238
239 #if defined(__GNUC__) && !defined(__clang__)
240 #pragma GCC diagnostic pop
241 #endif
242
243 template<class T>
244 const T* get_pointer(const Optional<T>& opt) {
245   return opt ? &opt.value() : nullptr;
246 }
247
248 template<class T>
249 T* get_pointer(Optional<T>& opt) {
250   return opt ? &opt.value() : nullptr;
251 }
252
253 template<class T>
254 void swap(Optional<T>& a, Optional<T>& b) {
255   if (a.hasValue() && b.hasValue()) {
256     // both full
257     using std::swap;
258     swap(a.value(), b.value());
259   } else if (a.hasValue() || b.hasValue()) {
260     std::swap(a, b); // fall back to default implementation if they're mixed.
261   }
262 }
263
264 template<class T,
265          class Opt = Optional<typename std::decay<T>::type>>
266 Opt make_optional(T&& v) {
267   return Opt(std::forward<T>(v));
268 }
269
270 template<class V>
271 bool operator< (const Optional<V>& a, const Optional<V>& b) {
272   if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
273   if (a.hasValue())                 { return a.value()    < b.value(); }
274   return false;
275 }
276
277 template<class V>
278 bool operator==(const Optional<V>& a, const Optional<V>& b) {
279   if (a.hasValue() != b.hasValue()) { return false; }
280   if (a.hasValue())                 { return a.value() == b.value(); }
281   return true;
282 }
283
284 template<class V>
285 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
286   return !(b < a);
287 }
288
289 template<class V>
290 bool operator!=(const Optional<V>& a, const Optional<V>& b) {
291   return !(b == a);
292 }
293
294 template<class V>
295 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
296   return !(a < b);
297 }
298
299 template<class V>
300 bool operator> (const Optional<V>& a, const Optional<V>& b) {
301   return b < a;
302 }
303
304 // To supress comparability of Optional<T> with T, despite implicit conversion.
305 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
306 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
307 template<class V> bool operator==(const Optional<V>&, const V& other) = delete;
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 V& other, const Optional<V>&) = delete;
312 template<class V> bool operator<=(const V& other, const Optional<V>&) = delete;
313 template<class V> bool operator==(const V& other, const Optional<V>&) = 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
318 } // namespace folly
319
320 #endif//FOLLY_OPTIONAL_H_