Debian Codegraph @

src/dmlc-core/include/dmlc/optional.h

raw symbols SCIP
1 /*!
2 * Copyright (c) 2016 by Contributors
3 * \file optional.h
4 * \brief Container to hold optional data.
5 */
6 #ifndef DMLC_OPTIONAL_H_
7 #define DMLC_OPTIONAL_H_
8
9 #include <algorithm>
10 #include <iostream>
11 #include <string>
12 #include <utility>
13
14 #include "./base.h"
15 #include "./common.h"
16 #include "./logging.h"
17 #include "./type_traits.h"
18
19 namespace dmlc {
20
21 /*! \brief dummy type for assign null to optional */
22 struct nullopt_t {
23 #if defined(_MSC_VER) && _MSC_VER < 1900
24 /*! \brief dummy constructor */
25 explicit nullopt_t(int a) {}
26 #else
27 /*! \brief dummy constructor */
28 constexpr explicit nullopt_t(int) {}
29 #endif
30 };
31
32 /*! Assign null to optional: optional<T> x = nullopt; */
33 constexpr const nullopt_t nullopt = nullopt_t(0);
34 /*! \brief C++14 aliases */
35 template <typename T>
36 using decay_t = typename std::decay<T>::type;
37 template <bool B, typename T = void>
38 using enable_if_t = typename std::enable_if<B, T>::type;
39
40 /*! \brief disambiguation tags that can be passed to the constructors of
41 * dmlc::optional. A tag type to tell constructor to construct its value in-place
42 */
43 struct in_place_t {
44 explicit in_place_t() = default; // NOLINT(*)
45 };
46 /*! \brief A tag to tell constructor to construct its value in-place */
47 static constexpr in_place_t in_place{};
48
49 /*! \brief Is not constructible or convertible from any expression of type
50 (possibly const) dmlc::optional<U>, i.e., the following 8 type traits are all
51 false: Link: https://en.cppreference.com/w/cpp/utility/optional/optional */
52 template <typename T>
53 class optional;
54 template <typename T, typename U, typename Other>
55 using enable_constructor_from_other
56 = enable_if_t<std::is_constructible<T, Other>::value
57 && !std::is_constructible<T, optional<U> &>::value
58 && !std::is_constructible<T, optional<U> &&>::value
59 && !std::is_convertible<optional<U> &, T>::value
60 && !std::is_convertible<optional<U> &&, T>::value
61 && !std::is_constructible<T, const optional<U> &>::value
62 && !std::is_constructible<T, const optional<U> &&>::value
63 && !std::is_convertible<const optional<U> &, T>::value
64 && !std::is_convertible<const optional<U> &&, T>::value>;
65 template <typename T, typename U>
66 using enable_constructor_from_value = enable_if_t<std::is_constructible<T, U &&>::value
67 && !std::is_same<decay_t<U>, in_place_t>::value
68 && !std::is_same<optional<T>, decay_t<U>>::value>;
69 /*!
70 * \brief c++17 compatible optional class.
71 *
72 * At any time an optional<T> instance either
73 * hold no value (string representation "None")
74 * or hold a value of type T.
75 */
76 template <typename T>
77 class optional {
78 public:
79 using value_type = T;
80 /*! \brief constructs an object that does not contain a value. */
81 optional() : is_none(true) {}
82 /*! \brief constructs an object that does contain a nullopt value. */
83 optional(dmlc::nullopt_t) noexcept : is_none(true) {} // NOLINT(*)
84 /*! \brief construct an optional object with another optional object */
85 optional(const optional<T> &other) {
86
87 #if __GNUC__ >= 6
88
89 #endif
90 is_none = other.is_none;
91 if (!is_none) {
92 new (&val) T(other.value());
93 }
94
95 }
96 /*! \brief move constructor: If other contains a value, then stored value is
97 * direct-intialized with it. */
98 optional(optional &&other) noexcept(
99 std::is_nothrow_move_constructible<T>::value && std::is_nothrow_move_assignable<T>::value) {
100 if (!other.has_value()) {
101 reset();
102 } else if (has_value()) {
103 **this = std::move(*other);
104 } else {
105 new (&val) T(std::move(*other));
106 is_none = false;
107 }
108 }
109 /*! \brief constructs an optional object that contains a value, initialized as
110 * if direct-initializing */
111 template <typename... Args>
112 explicit optional(
113 enable_if_t<std::is_constructible<T, Args...>::value, in_place_t>, Args &&...args) {
114 new (&val) T(std::forward<Args>(args)...);
115 is_none = false;
116 }
117 /*! \brief Constructs an optional object that contains a value, initialized as
118 * if direct-initializing */
119 template <typename U, typename... Args>
120 explicit optional(
121 enable_if_t<std::is_constructible<T, std::initializer_list<U> &, Args &&...>::value,
122 in_place_t>,
123 std::initializer_list<U> ilist, Args &&...args) {
124 construct(ilist, std::forward<Args>(args)...);
125 }
126 /*! \brief constructs the stored value with value with `other` parameter.*/
127 template <typename U = value_type, enable_if_t<std::is_convertible<U &&, T>::value> * = nullptr,
128 enable_constructor_from_value<T, U> * = nullptr>
129 optional(U &&other) noexcept { // NOLINT(*)
130 new (&val) T(std::forward<U>(other));
131 is_none = false;
132 }
133 /*! \brief explicit constructor: constructs the stored value with `other`
134 * parameter. */
135 template <typename U = value_type, enable_if_t<!std::is_convertible<U &&, T>::value> * = nullptr,
136 enable_constructor_from_value<T, U> * = nullptr>
137 explicit optional(U &&other) noexcept {
138 new (&val) T(std::forward<U>(other));
139 is_none = false;
140 }
141 /*! \brief converting copy constructor */
142 template <typename U, enable_constructor_from_other<T, U, const U &> * = nullptr,
143 enable_if_t<std::is_convertible<const U &, T>::value> * = nullptr>
144 optional(const optional<U> &other) {
145 if (other.has_value()) {
146 construct(*other);
147 }
148 }
149 /*! \brief explicit converting copy constructor */
150 template <typename U, enable_constructor_from_other<T, U, const U &> * = nullptr,
151 enable_if_t<!std::is_convertible<const U &, T>::value> * = nullptr>
152 explicit optional(const optional<U> &other) {
153 if (other.has_value()) {
154 construct(*other);
155 }
156 }
157 /*! \brief converting move constructor */
158 template <typename U, enable_constructor_from_other<T, U, U &&> * = nullptr,
159 enable_if_t<std::is_convertible<U &&, T>::value> * = nullptr>
160 optional(optional<U> &&other) {
161 if (other.has_value()) {
162 construct(std::move(*other));
163 }
164 }
165 /*! \brief explicit converting move constructor */
166 template <typename U, enable_constructor_from_other<T, U, U &&> * = nullptr,
167 enable_if_t<!std::is_convertible<U &&, T>::value> * = nullptr>
168 explicit optional(optional<U> &&other) {
169 if (other.has_value()) {
170 construct(std::move(*other));
171 }
172 }
173 /*! \brief reset */
174 void reset() noexcept {
175 if (!has_value()) {
176 return;
177 }
178 (**this).T::~T();
179 is_none = true;
180 }
181 /*! \brief deconstructor */
182 ~optional() {
183 if (!is_none) {
184 reinterpret_cast<T *>(&val)->~T();
185 }
186 }
187 /*! \brief swap two optional */
188 void swap(optional<T> &other) {
189 std::swap(val, other.val);
190 std::swap(is_none, other.is_none);
191 }
192 /*! \brief set this object to hold value
193 * \param value the value to hold
194 * \return return self to support chain assignment
195 */
196 optional<T> &operator=(const T &value) {
197 (optional<T>(value)).swap(*this);
198 return *this;
199 }
200 /*! \brief set this object to hold the same value with other
201 * \param other the other object
202 * \return return self to support chain assignment
203 */
204 optional<T> &operator=(const optional<T> &other) {
205
206 #if __GNUC__ >= 6
207
208 #endif
209 (optional<T>(other)).swap(*this);
210 return *this;
211
212 }
213 /*! \brief clear the value this object is holding.
214 * optional<T> x = nullopt;
215 */
216 optional<T> &operator=(nullopt_t) {
217 (optional<T>()).swap(*this);
218 return *this;
219 }
220 /*! \brief non-const dereference operator */
221 T &operator*() { // NOLINT(*)
222 return *reinterpret_cast<T *>(&val);
223 }
224 /*! \brief const dereference operator */
225 const T &operator*() const {
226 return *reinterpret_cast<const T *>(&val);
227 }
228 /*! \brief equal comparison */
229 bool operator==(const optional<T> &other) const {
230 return this->is_none == other.is_none
231 && (this->is_none == true || this->value() == other.value());
232 }
233 /*! \brief return the holded value.
234 * throws std::logic_error if holding no value
235 */
236 T &value() & {
237 if (is_none) {
238 throw std::logic_error("bad optional access");
239 }
240 return *reinterpret_cast<T *>(&val);
241 }
242 const T &value() const & {
243 if (is_none) {
244 throw std::logic_error("bad optional access");
245 }
246 return *reinterpret_cast<const T *>(&val);
247 }
248 T &&value() && {
249 if (is_none) {
250 throw std::logic_error("bad optional access");
251 }
252 return std::move(value());
253 }
254 const T &&value() const && {
255 if (is_none) {
256 throw std::logic_error("bad optional access");
257 }
258 return std::move(value());
259 }
260 /*! \brief whether this object is holding a value */
261 explicit operator bool() const {
262 return !is_none;
263 }
264 /*! \brief whether this object is holding a value (alternate form). */
265 bool has_value() const {
266 return operator bool();
267 }
268
269 private:
270 // whether this is none
271 bool is_none = true;
272 // on stack storage of value
273 typename std::aligned_storage<sizeof(T), alignof(T)>::type val;
274
275 template <typename... Args>
276 void construct(Args &&...args) noexcept {
277 new (std::addressof(val)) T(std::forward<Args>(args)...);
278 is_none = false;
279 }
280 };
281
282 /*! \brief serialize an optional object to string.
283 *
284 * \code
285 * dmlc::optional<int> x;
286 * std::cout << x; // None
287 * x = 0;
288 * std::cout << x; // 0
289 * \endcode
290 *
291 * \param os output stream
292 * \param t source optional<T> object
293 * \return output stream
294 */
295 template <typename T>
296 std::ostream &operator<<(std::ostream &os, const optional<T> &t) {
297 if (t) {
298 os << *t;
299 } else {
300 os << "None";
301 }
302 return os;
303 }
304
305 /*! \brief parse a string object into optional<T>
306 *
307 * \code
308 * dmlc::optional<int> x;
309 * std::string s1 = "1";
310 * std::istringstream is1(s1);
311 * s1 >> x; // x == optional<int>(1)
312 *
313 * std::string s2 = "None";
314 * std::istringstream is2(s2);
315 * s2 >> x; // x == optional<int>()
316 * \endcode
317 *
318 * \param is input stream
319 * \param t target optional<T> object
320 * \return input stream
321 */
322 template <typename T>
323 std::istream &operator>>(std::istream &is, optional<T> &t) {
324 char buf[4];
325 std::streampos origin = is.tellg();
326 is.read(buf, 4);
327 if (is.fail() || buf[0] != 'N' || buf[1] != 'o' || buf[2] != 'n' || buf[3] != 'e') {
328 is.clear();
329 is.seekg(origin);
330 T x;
331 is >> x;
332 t = x;
333 if (std::is_integral<T>::value && !is.eof() && is.peek() == 'L') {
334 is.get();
335 }
336 } else {
337 t = nullopt;
338 }
339 return is;
340 }
341 /*! \brief specialization of '>>' istream parsing for optional<bool>
342 *
343 * Permits use of generic parameter FieldEntry<DType> class to create
344 * FieldEntry<optional<bool>> without explicit specialization.
345 *
346 * \code
347 * dmlc::optional<bool> x;
348 * std::string s1 = "true";
349 * std::istringstream is1(s1);
350 * s1 >> x; // x == optional<bool>(true)
351 *
352 * std::string s2 = "None";
353 * std::istringstream is2(s2);
354 * s2 >> x; // x == optional<bool>()
355 * \endcode
356 *
357 * \param is input stream
358 * \param t target optional<bool> object
359 * \return input stream
360 */
361 inline std::istream &operator>>(std::istream &is, optional<bool> &t) {
362 // Discard initial whitespace
363 while (isspace(is.peek())) {
364 is.get();
365 }
366 // Extract chars that might be valid into a separate string, stopping
367 // on whitespace or other non-alphanumerics such as ",)]".
368 std::string s;
369 while (isalnum(is.peek())) {
370 s.push_back(is.get());
371 }
372
373 if (!is.fail()) {
374 std::transform(s.begin(), s.end(), s.begin(), ::tolower);
375 if (s == "1" || s == "true") {
376 t = true;
377 } else if (s == "0" || s == "false") {
378 t = false;
379 } else if (s == "none") {
380 t = nullopt;
381 } else {
382 is.setstate(std::ios::failbit);
383 }
384 }
385
386 return is;
387 }
388
389 /*! \brief description for optional int */
390 DMLC_DECLARE_TYPE_NAME(optional<int>, "int or None");
391 /*! \brief description for optional bool */
392 DMLC_DECLARE_TYPE_NAME(optional<bool>, "boolean or None");
393 /*! \brief description for optional float */
394 DMLC_DECLARE_TYPE_NAME(optional<float>, "float or None");
395 /*! \brief description for optional double */
396 DMLC_DECLARE_TYPE_NAME(optional<double>, "double or None");
397
398 } // namespace dmlc
399
400 namespace std {
401 /*! \brief std hash function for optional */
402 template <typename T>
403 struct hash<dmlc::optional<T>> {
404 /*!
405 * \brief returns hash of the optional value.
406 * \param val value.
407 * \return hash code.
408 */
409 size_t operator()(const dmlc::optional<T> &val) const {
410 std::hash<bool> hash_bool;
411 size_t res = hash_bool(val.has_value());
412 if (val.has_value()) {
413 res = dmlc::HashCombine(res, val.value());
414 }
415 return res;
416 }
417 };
418 } // namespace std
419
420 #endif // DMLC_OPTIONAL_H_