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