blob: b047fabc427871ee9d86fdc3f7ef6397c0f82a46 [file] [log] [blame]
Karl Wibergbe579832015-11-10 22:34:18 +01001/*
2 * Copyright 2015 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef WEBRTC_BASE_OPTIONAL_H_
12#define WEBRTC_BASE_OPTIONAL_H_
13
14#include <algorithm>
kwibergbfefb032016-05-01 14:53:46 -070015#include <memory>
Karl Wibergbe579832015-11-10 22:34:18 +010016#include <utility>
17
kwiberg2b11fd22016-09-09 03:35:24 -070018#include "webrtc/base/array_view.h"
Karl Wibergbe579832015-11-10 22:34:18 +010019#include "webrtc/base/checks.h"
kwiberg2b11fd22016-09-09 03:35:24 -070020#include "webrtc/base/sanitizer.h"
Karl Wibergbe579832015-11-10 22:34:18 +010021
22namespace rtc {
23
kwiberg2b11fd22016-09-09 03:35:24 -070024namespace optional_internal {
25
26#if RTC_HAS_ASAN
27
28// This is a non-inlined function. The optimizer can't see inside it.
29void* FunctionThatDoesNothingImpl(void*);
30
31template <typename T>
32inline T* FunctionThatDoesNothing(T* x) {
33 return reinterpret_cast<T*>(
34 FunctionThatDoesNothingImpl(reinterpret_cast<void*>(x)));
35}
36
37#else
38
39template <typename T>
40inline T* FunctionThatDoesNothing(T* x) { return x; }
41
42#endif
43
44} // namespace optional_internal
45
kwibergd0404802016-05-09 06:06:05 -070046// Simple std::optional-wannabe. It either contains a T or not.
Karl Wibergbe579832015-11-10 22:34:18 +010047//
48// A moved-from Optional<T> may only be destroyed, and assigned to if T allows
49// being assigned to after having been moved from. Specifically, you may not
50// assume that it just doesn't contain a value anymore.
51//
52// Examples of good places to use Optional:
53//
54// - As a class or struct member, when the member doesn't always have a value:
55// struct Prisoner {
56// std::string name;
57// Optional<int> cell_number; // Empty if not currently incarcerated.
58// };
59//
60// - As a return value for functions that may fail to return a value on all
61// allowed inputs. For example, a function that searches an array might
62// return an Optional<size_t> (the index where it found the element, or
63// nothing if it didn't find it); and a function that parses numbers might
64// return Optional<double> (the parsed number, or nothing if parsing failed).
65//
66// Examples of bad places to use Optional:
67//
68// - As a return value for functions that may fail because of disallowed
69// inputs. For example, a string length function should not return
70// Optional<size_t> so that it can return nothing in case the caller passed
71// it a null pointer; the function should probably use RTC_[D]CHECK instead,
72// and return plain size_t.
73//
74// - As a return value for functions that may fail to return a value on all
75// allowed inputs, but need to tell the caller what went wrong. Returning
76// Optional<double> when parsing a single number as in the example above
77// might make sense, but any larger parse job is probably going to need to
78// tell the caller what the problem was, not just that there was one.
79//
80// TODO(kwiberg): Get rid of this class when the standard library has
81// std::optional (and we're allowed to use it).
82template <typename T>
83class Optional final {
84 public:
85 // Construct an empty Optional.
kwiberg2b11fd22016-09-09 03:35:24 -070086 Optional() : has_value_(false), empty_('\0') {
87 PoisonValue();
88 }
Karl Wibergbe579832015-11-10 22:34:18 +010089
90 // Construct an Optional that contains a value.
kwibergd0404802016-05-09 06:06:05 -070091 explicit Optional(const T& value) : has_value_(true) {
92 new (&value_) T(value);
93 }
94 explicit Optional(T&& value) : has_value_(true) {
95 new (&value_) T(std::move(value));
96 }
Karl Wibergbe579832015-11-10 22:34:18 +010097
kwibergd0404802016-05-09 06:06:05 -070098 // Copy constructor: copies the value from m if it has one.
99 Optional(const Optional& m) : has_value_(m.has_value_) {
100 if (has_value_)
101 new (&value_) T(m.value_);
kwiberg2b11fd22016-09-09 03:35:24 -0700102 else
103 PoisonValue();
kwibergd0404802016-05-09 06:06:05 -0700104 }
Karl Wibergbe579832015-11-10 22:34:18 +0100105
kwibergd0404802016-05-09 06:06:05 -0700106 // Move constructor: if m has a value, moves the value from m, leaving m
107 // still in a state where it has a value, but a moved-from one (the
108 // properties of which depends on T; the only general guarantee is that we
109 // can destroy m).
110 Optional(Optional&& m) : has_value_(m.has_value_) {
111 if (has_value_)
112 new (&value_) T(std::move(m.value_));
kwiberg2b11fd22016-09-09 03:35:24 -0700113 else
114 PoisonValue();
kwibergd0404802016-05-09 06:06:05 -0700115 }
Karl Wibergbe579832015-11-10 22:34:18 +0100116
kwibergd0404802016-05-09 06:06:05 -0700117 ~Optional() {
118 if (has_value_)
119 value_.~T();
kwiberg2b11fd22016-09-09 03:35:24 -0700120 else
121 UnpoisonValue();
kwibergd0404802016-05-09 06:06:05 -0700122 }
123
124 // Copy assignment. Uses T's copy assignment if both sides have a value, T's
125 // copy constructor if only the right-hand side has a value.
126 Optional& operator=(const Optional& m) {
127 if (m.has_value_) {
128 if (has_value_) {
129 value_ = m.value_; // T's copy assignment.
130 } else {
kwiberg2b11fd22016-09-09 03:35:24 -0700131 UnpoisonValue();
kwibergd0404802016-05-09 06:06:05 -0700132 new (&value_) T(m.value_); // T's copy constructor.
133 has_value_ = true;
134 }
135 } else if (has_value_) {
136 value_.~T();
137 has_value_ = false;
kwiberg2b11fd22016-09-09 03:35:24 -0700138 PoisonValue();
kwibergd0404802016-05-09 06:06:05 -0700139 }
140 return *this;
141 }
142
143 // Move assignment. Uses T's move assignment if both sides have a value, T's
144 // move constructor if only the right-hand side has a value. The state of m
145 // after it's been moved from is as for the move constructor.
146 Optional& operator=(Optional&& m) {
147 if (m.has_value_) {
148 if (has_value_) {
149 value_ = std::move(m.value_); // T's move assignment.
150 } else {
kwiberg2b11fd22016-09-09 03:35:24 -0700151 UnpoisonValue();
kwibergd0404802016-05-09 06:06:05 -0700152 new (&value_) T(std::move(m.value_)); // T's move constructor.
153 has_value_ = true;
154 }
155 } else if (has_value_) {
156 value_.~T();
157 has_value_ = false;
kwiberg2b11fd22016-09-09 03:35:24 -0700158 PoisonValue();
kwibergd0404802016-05-09 06:06:05 -0700159 }
160 return *this;
161 }
162
163 // Swap the values if both m1 and m2 have values; move the value if only one
164 // of them has one.
Karl Wibergbe579832015-11-10 22:34:18 +0100165 friend void swap(Optional& m1, Optional& m2) {
kwibergd0404802016-05-09 06:06:05 -0700166 if (m1.has_value_) {
167 if (m2.has_value_) {
168 // Both have values: swap.
169 using std::swap;
170 swap(m1.value_, m2.value_);
171 } else {
172 // Only m1 has a value: move it to m2.
kwiberg2b11fd22016-09-09 03:35:24 -0700173 m2.UnpoisonValue();
kwibergd0404802016-05-09 06:06:05 -0700174 new (&m2.value_) T(std::move(m1.value_));
175 m1.value_.~T(); // Destroy the moved-from value.
176 m1.has_value_ = false;
177 m2.has_value_ = true;
kwiberg2b11fd22016-09-09 03:35:24 -0700178 m1.PoisonValue();
kwibergd0404802016-05-09 06:06:05 -0700179 }
180 } else if (m2.has_value_) {
181 // Only m2 has a value: move it to m1.
kwiberg2b11fd22016-09-09 03:35:24 -0700182 m1.UnpoisonValue();
kwibergd0404802016-05-09 06:06:05 -0700183 new (&m1.value_) T(std::move(m2.value_));
184 m2.value_.~T(); // Destroy the moved-from value.
185 m1.has_value_ = true;
186 m2.has_value_ = false;
kwiberg2b11fd22016-09-09 03:35:24 -0700187 m2.PoisonValue();
kwibergd0404802016-05-09 06:06:05 -0700188 }
Karl Wibergbe579832015-11-10 22:34:18 +0100189 }
190
191 // Conversion to bool to test if we have a value.
192 explicit operator bool() const { return has_value_; }
193
194 // Dereferencing. Only allowed if we have a value.
195 const T* operator->() const {
196 RTC_DCHECK(has_value_);
197 return &value_;
198 }
199 T* operator->() {
200 RTC_DCHECK(has_value_);
201 return &value_;
202 }
203 const T& operator*() const {
204 RTC_DCHECK(has_value_);
205 return value_;
206 }
207 T& operator*() {
208 RTC_DCHECK(has_value_);
209 return value_;
210 }
211
212 // Dereference with a default value in case we don't have a value.
213 const T& value_or(const T& default_val) const {
kwiberg2b11fd22016-09-09 03:35:24 -0700214 // The no-op call prevents the compiler from generating optimized code that
215 // reads value_ even if !has_value_, but only if FunctionThatDoesNothing is
216 // not completely inlined; see its declaration.).
217 return has_value_ ? *optional_internal::FunctionThatDoesNothing(&value_)
218 : default_val;
Karl Wibergbe579832015-11-10 22:34:18 +0100219 }
220
221 // Equality tests. Two Optionals are equal if they contain equivalent values,
222 // or
223 // if they're both empty.
224 friend bool operator==(const Optional& m1, const Optional& m2) {
225 return m1.has_value_ && m2.has_value_ ? m1.value_ == m2.value_
226 : m1.has_value_ == m2.has_value_;
227 }
228 friend bool operator!=(const Optional& m1, const Optional& m2) {
229 return m1.has_value_ && m2.has_value_ ? m1.value_ != m2.value_
230 : m1.has_value_ != m2.has_value_;
231 }
232
233 private:
kwiberg2b11fd22016-09-09 03:35:24 -0700234 // Tell sanitizers that value_ shouldn't be touched.
235 void PoisonValue() {
236 rtc::AsanPoison(rtc::MakeArrayView(&value_, 1));
237 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&value_, 1));
238 }
239
240 // Tell sanitizers that value_ is OK to touch again.
241 void UnpoisonValue() {
242 rtc::AsanUnpoison(rtc::MakeArrayView(&value_, 1));
243 }
244
kwibergd0404802016-05-09 06:06:05 -0700245 bool has_value_; // True iff value_ contains a live value.
246 union {
ossuea416942016-06-30 02:14:54 -0700247 // empty_ exists only to make it possible to initialize the union, even when
248 // it doesn't contain any data. If the union goes uninitialized, it may
249 // trigger compiler warnings.
250 char empty_;
kwibergd0404802016-05-09 06:06:05 -0700251 // By placing value_ in a union, we get to manage its construction and
252 // destruction manually: the Optional constructors won't automatically
253 // construct it, and the Optional destructor won't automatically destroy
254 // it. Basically, this just allocates a properly sized and aligned block of
255 // memory in which we can manually put a T with placement new.
256 T value_;
257 };
Karl Wibergbe579832015-11-10 22:34:18 +0100258};
259
260} // namespace rtc
261
262#endif // WEBRTC_BASE_OPTIONAL_H_