OLD | NEW |
(Empty) | |
| 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #ifndef HEADLESS_PUBLIC_UTIL_MAYBE_H_ |
| 6 #define HEADLESS_PUBLIC_UTIL_MAYBE_H_ |
| 7 |
| 8 #include <algorithm> |
| 9 |
| 10 #include "base/logging.h" |
| 11 #include "base/macros.h" |
| 12 |
| 13 namespace headless { |
| 14 |
| 15 // A simple Maybe which may or may not have a value. Based on v8::Maybe. |
| 16 template <typename T> |
| 17 class Maybe { |
| 18 public: |
| 19 Maybe() : has_value_(false) {} |
| 20 |
| 21 bool IsNothing() const { return !has_value_; } |
| 22 bool IsJust() const { return has_value_; } |
| 23 |
| 24 // Will crash if the Maybe<> is nothing. |
| 25 T& FromJust() { |
| 26 DCHECK(IsJust()); |
| 27 return value_; |
| 28 } |
| 29 const T& FromJust() const { |
| 30 DCHECK(IsJust()); |
| 31 return value_; |
| 32 } |
| 33 |
| 34 T FromMaybe(const T& default_value) const { |
| 35 return has_value_ ? value_ : default_value; |
| 36 } |
| 37 |
| 38 bool operator==(const Maybe& other) const { |
| 39 return (IsJust() == other.IsJust()) && |
| 40 (!IsJust() || FromJust() == other.FromJust()); |
| 41 } |
| 42 |
| 43 bool operator!=(const Maybe& other) const { return !operator==(other); } |
| 44 |
| 45 Maybe& operator=(Maybe&& other) { |
| 46 has_value_ = other.has_value_; |
| 47 value_ = std::move(other.value_); |
| 48 return *this; |
| 49 } |
| 50 |
| 51 Maybe& operator=(const Maybe& other) { |
| 52 has_value_ = other.has_value_; |
| 53 value_ = other.value_; |
| 54 return *this; |
| 55 } |
| 56 |
| 57 Maybe(const Maybe& other) = default; |
| 58 Maybe(Maybe&& other) = default; |
| 59 |
| 60 private: |
| 61 template <class U> |
| 62 friend Maybe<U> Nothing(); |
| 63 template <class U> |
| 64 friend Maybe<U> Just(const U& u); |
| 65 template <class U> |
| 66 friend Maybe<typename std::remove_reference<U>::type> Just(U&& u); |
| 67 |
| 68 explicit Maybe(const T& t) : has_value_(true), value_(t) {} |
| 69 explicit Maybe(T&& t) : has_value_(true), value_(std::move(t)) {} |
| 70 |
| 71 bool has_value_; |
| 72 T value_; |
| 73 }; |
| 74 |
| 75 template <class T> |
| 76 Maybe<T> Nothing() { |
| 77 return Maybe<T>(); |
| 78 } |
| 79 |
| 80 template <class T> |
| 81 Maybe<T> Just(const T& t) { |
| 82 return Maybe<T>(t); |
| 83 } |
| 84 |
| 85 template <class T> |
| 86 Maybe<typename std::remove_reference<T>::type> Just(T&& t) { |
| 87 return Maybe<typename std::remove_reference<T>::type>(std::move(t)); |
| 88 } |
| 89 |
| 90 } // namespace headless |
| 91 |
| 92 #endif // HEADLESS_PUBLIC_UTIL_MAYBE_H_ |
OLD | NEW |