Remove Stream
[folly.git] / folly / Optional.h
1 /*
2  * Copyright 2012 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 namespace folly {
65
66 namespace detail { struct NoneHelper {}; }
67
68 typedef int detail::NoneHelper::*None;
69
70 const None none = nullptr;
71
72 /**
73  * gcc-4.7 warns about use of uninitialized memory around the use of storage_
74  * even though this is explicitly initialized at each point.
75  */
76 #pragma GCC diagnostic push
77 #pragma GCC diagnostic ignored "-Wuninitialized"
78
79 template<class Value>
80 class Optional : boost::totally_ordered<Optional<Value>,
81                  boost::totally_ordered<Optional<Value>, Value>> {
82   typedef void (Optional::*bool_type)() const;
83   void truthy() const {};
84  public:
85   static_assert(!std::is_reference<Value>::value,
86                 "Optional may not be used with reference types");
87
88   Optional()
89     : hasValue_(false) {
90   }
91
92   Optional(const Optional& src) {
93     if (src.hasValue()) {
94       construct(src.value());
95     } else {
96       hasValue_ = false;
97     }
98   }
99
100   Optional(Optional&& src) {
101     if (src.hasValue()) {
102       construct(std::move(src.value()));
103       src.clear();
104     } else {
105       hasValue_ = false;
106     }
107   }
108
109   /* implicit */ Optional(const None& empty)
110     : hasValue_(false) {
111   }
112
113   /* implicit */ Optional(Value&& newValue) {
114     construct(std::move(newValue));
115   }
116
117   /* implicit */ Optional(const Value& newValue) {
118     construct(newValue);
119   }
120
121   ~Optional() {
122     clear();
123   }
124
125   void assign(const None&) {
126     clear();
127   }
128
129   void assign(Optional&& src) {
130     if (src.hasValue()) {
131       assign(std::move(src.value()));
132       src.clear();
133     } else {
134       clear();
135     }
136   }
137
138   void assign(const Optional& src) {
139     if (src.hasValue()) {
140       assign(src.value());
141     } else {
142       clear();
143     }
144   }
145
146   void assign(Value&& newValue) {
147     if (hasValue()) {
148       value_ = std::move(newValue);
149     } else {
150       construct(std::move(newValue));
151     }
152   }
153
154   void assign(const Value& newValue) {
155     if (hasValue()) {
156       value_ = newValue;
157     } else {
158       construct(newValue);
159     }
160   }
161
162   template<class Arg>
163   Optional& operator=(Arg&& arg) {
164     assign(std::forward<Arg>(arg));
165     return *this;
166   }
167
168   bool operator<(const Optional& other) const {
169     if (hasValue() != other.hasValue()) {
170       return hasValue() < other.hasValue();
171     }
172     if (hasValue()) {
173       return value() < other.value();
174     }
175     return false; // both empty
176   }
177
178   bool operator<(const Value& other) const {
179     return !hasValue() || value() < other;
180   }
181
182   bool operator==(const Optional& other) const {
183     if (hasValue()) {
184       return other.hasValue() && value() == other.value();
185     } else {
186       return !other.hasValue();
187     }
188   }
189
190   bool operator==(const Value& other) const {
191     return hasValue() && value() == other;
192   }
193
194   template<class... Args>
195   void emplace(Args&&... args) {
196     clear();
197     construct(std::forward<Args>(args)...);
198   }
199
200   void clear() {
201     if (hasValue()) {
202       hasValue_ = false;
203       value_.~Value();
204     }
205   }
206
207   const Value& value() const {
208     assert(hasValue());
209     return value_;
210   }
211
212   Value& value() {
213     assert(hasValue());
214     return value_;
215   }
216
217   bool hasValue() const { return hasValue_; }
218
219   /* safe bool idiom */
220   operator bool_type() const {
221     return hasValue() ? &Optional::truthy : nullptr;
222   }
223
224   const Value& operator*() const { return value(); }
225         Value& operator*()       { return value(); }
226
227   const Value* operator->() const { return &value(); }
228         Value* operator->()       { return &value(); }
229
230  private:
231   template<class... Args>
232   void construct(Args&&... args) {
233     const void* ptr = &value_;
234     // for supporting const types
235     new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
236     hasValue_ = true;
237   }
238
239   // uninitialized
240   union { Value value_; };
241   bool hasValue_;
242 };
243
244 #pragma GCC diagnostic pop
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 }// namespace folly
268
269 #endif//FOLLY_OPTIONAL_H_