Repository navigation
Expand file tree
/
Copy pathstatus_or.h
More file actions
366 lines (332 loc) · 10.6 KB
/
Copy pathstatus_or.h
File metadata and controls
366 lines (332 loc) · 10.6 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright 2018 Google LLC
//
// 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 GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STATUS_OR_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STATUS_OR_H
#include "google/cloud/internal/throw_delegate.h"
#include "google/cloud/status.h"
#include "google/cloud/version.h"
#include <type_traits>
#include <utility>
namespace google {
namespace cloud {
inline namespace GOOGLE_CLOUD_CPP_NS {
/**
* Holds a value or a `Status` indicating why there is no value.
*
* `StatusOr<T>` represents either a usable `T` value or a `Status` object
* explaining why a `T` value is not present. Typical usage of `StatusOr<T>`
* looks like usage of a smart pointer, or even a std::optional<T>, in that you
* first check its validity using a conversion to bool (or by calling
* `StatusOr::ok()`), then you may dereference the object to access the
* contained value. It is undefined behavior (UB) to dereference a
* `StatusOr<T>` that is not "ok". For example:
*
* @code
* StatusOr<Foo> foo = FetchFoo();
* if (!foo) { // Same as !foo.ok()
* // handle error and probably look at foo.status()
* } else {
* foo->DoSomethingFooey(); // UB if !foo
* }
* @endcode
*
* Alternatively, you may call the `StatusOr::value()` member function,
* which is defined to throw an exception if there is no `T` value, or crash
* the program if exceptions are disabled. It is never UB to call
* `.value()`.
*
* @code
* StatusOr<Foo> foo = FetchFoo();
* foo.value().DoSomethingFooey(); // May throw/crash if there is no value
* @endcode
*
* Functions that can fail will often return a `StatusOr<T>` instead of
* returning an error code and taking a `T` out-param, or rather than directly
* returning the `T` and throwing an exception on error. StatusOr is used so
* that callers can choose whether they want to explicitly check for errors,
* crash the program, or throw exceptions. Since constructors do not have a
* return value, they should be designed in such a way that they cannot fail by
* moving the object's complex initialization logic into a separate factory
* function that itself can return a `StatusOr<T>`. For example:
*
* @code
* class Bar {
* public:
* Bar(Arg arg);
* ...
* };
* StatusOr<Bar> MakeBar() {
* ... complicated logic that might fail
* return Bar(std::move(arg));
* }
* @endcode
*
* `StatusOr<T>` supports equality comparisons if the underlying type `T` does.
*
* TODO(...) - the current implementation is fairly naive with respect to `T`,
* it is unlikely to work correctly for reference types, types without default
* constructors, arrays.
*
* @tparam T the type of the value.
*/
template <typename T>
class StatusOr final {
public:
/**
* A `value_type` member for use in generic programming.
*
* This is analogous to that of `std::optional::value_type`.
*/
using value_type = T;
/**
* Initializes with an error status (UNKNOWN).
*
* TODO(#548) - currently storage::Status does not define the status codes,
* they are simply integers, usually HTTP status codes. We need to map to
* the well-defined set of status codes.
*/
StatusOr() : StatusOr(Status(StatusCode::kUnknown, "default")) {}
/**
* Creates a new `StatusOr<T>` holding the error condition @p rhs.
*
* @par Post-conditions
* `ok() == false` and `status() == rhs`.
*
* @param rhs the status to initialize the object.
* @throws std::invalid_argument if `rhs.ok()`. If exceptions are disabled the
* program terminates via `google::cloud::Terminate()`
*/
// NOLINTNEXTLINE(google-explicit-constructor)
StatusOr(Status rhs) : status_(std::move(rhs)) {
if (status_.ok()) {
google::cloud::internal::ThrowInvalidArgument(__func__);
}
}
/**
* Assigns the given non-OK Status to this `StatusOr<T>`.
*
* @throws std::invalid_argument if `status.ok()`. If exceptions are disabled
* the program terminates via `google::cloud::Terminate()`
*/
StatusOr& operator=(Status status) {
*this = StatusOr(std::move(status));
return *this;
}
// NOLINTNEXTLINE(performance-noexcept-move-constructor)
StatusOr(StatusOr&& rhs) noexcept(noexcept(T(std::move(*rhs))))
: status_(std::move(rhs.status_)) {
if (status_.ok()) {
new (&value_) T(std::move(*rhs));
}
}
// NOLINTNEXTLINE(performance-noexcept-move-constructor)
StatusOr& operator=(StatusOr&& rhs) noexcept(noexcept(T(std::move(*rhs)))) {
// There may be shorter ways to express this, but this is fairly readable,
// and should be reasonably efficient. Note that we must avoid destructing
// the destination and/or default initializing it unless really needed.
if (!ok()) {
if (!rhs.ok()) {
status_ = std::move(rhs.status_);
return *this;
}
new (&value_) T(std::move(*rhs));
status_ = Status();
return *this;
}
if (!rhs.ok()) {
value_.~T();
status_ = std::move(rhs.status_);
return *this;
}
**this = *std::move(rhs);
status_ = Status();
return *this;
}
StatusOr(StatusOr const& rhs) : status_(rhs.status_) {
if (status_.ok()) {
new (&value_) T(*rhs);
}
}
StatusOr& operator=(StatusOr const& rhs) {
// There may be shorter ways to express this, but this is fairly readable,
// and should be reasonably efficient. Note that we must avoid destructing
// the destination and/or default initializing it unless really needed.
if (!ok()) {
if (!rhs.ok()) {
status_ = rhs.status_;
return *this;
}
new (&value_) T(*rhs);
status_ = rhs.status_;
return *this;
}
if (!rhs.ok()) {
value_.~T();
status_ = rhs.status_;
return *this;
}
**this = *rhs;
status_ = rhs.status_;
return *this;
}
~StatusOr() {
if (ok()) {
value_.~T();
}
}
/**
* Assign a `T` (or anything convertible to `T`) into the `StatusOr`.
*/
// Disable this assignment if U==StatusOr<T>. Well, really if U is a
// cv-qualified version of StatusOr<T>, so we need to apply std::decay<> to
// it first.
template <typename U = T>
typename std::enable_if< // NOLINT(misc-unconventional-assign-operator)
!std::is_same<StatusOr, typename std::decay<U>::type>::value,
StatusOr>::type&
operator=(U&& rhs) {
// There may be shorter ways to express this, but this is fairly readable,
// and should be reasonably efficient. Note that we must avoid destructing
// the destination and/or default initializing it unless really needed.
if (!ok()) {
new (&value_) T(std::forward<U>(rhs));
status_ = Status();
return *this;
}
**this = std::forward<U>(rhs);
status_ = Status();
return *this;
}
/**
* Creates a new `StatusOr<T>` holding the value @p rhs.
*
* @par Post-conditions
* `ok() == true` and `value() == rhs`.
*
* @param rhs the value used to initialize the object.
*
* @throws only if `T`'s move constructor throws.
*/
// NOLINTNEXTLINE(google-explicit-constructor)
StatusOr(T&& rhs) { new (&value_) T(std::move(rhs)); }
// NOLINTNEXTLINE(google-explicit-constructor)
StatusOr(T const& rhs) { new (&value_) T(rhs); }
bool ok() const { return status_.ok(); }
explicit operator bool() const { return status_.ok(); }
//@{
/**
* @name Deference operators.
*
* @warning Using these operators when `ok() == false` results in undefined
* behavior.
*
* @return All these return a (properly ref and const-qualified) reference to
* the underlying value.
*/
T& operator*() & { return value_; }
T const& operator*() const& { return value_; }
T&& operator*() && { return std::move(value_); }
T const&& operator*() const&& { return std::move(value_); }
//@}
//@{
/**
* @name Member access operators.
*
* @warning Using these operators when `ok() == false` results in undefined
* behavior.
*
* @return All these return a (properly ref and const-qualified) pointer to
* the underlying value.
*/
T* operator->() & { return &value_; }
T const* operator->() const& { return &value_; }
//@}
//@{
/**
* @name Value accessors.
*
* @return All these member functions return a (properly ref and
* const-qualified) reference to the underlying value.
*
* @throws `RuntimeStatusError` with the contents of `status()` if the object
* does not contain a value, i.e., if `ok() == false`.
*/
T& value() & {
CheckHasValue();
return **this;
}
T const& value() const& {
CheckHasValue();
return **this;
}
T&& value() && {
CheckHasValue();
return std::move(**this);
}
T const&& value() const&& {
CheckHasValue();
return std::move(**this);
}
//@}
//@{
/**
* @name Status accessors.
*
* @return All these member functions return the (properly ref and
* const-qualified) status. If the object contains a value then
* `status().ok() == true`.
*/
Status& status() & { return status_; }
Status const& status() const& { return status_; }
Status&& status() && { return std::move(status_); }
Status const&& status() const&& { return std::move(status_); }
//@}
private:
void CheckHasValue() const& {
if (!ok()) {
internal::ThrowStatus(status_);
}
}
// When possible, do not copy the status.
void CheckHasValue() && {
if (!ok()) {
internal::ThrowStatus(std::move(status_));
}
}
Status status_;
union {
T value_;
};
};
// Returns true IFF both `StatusOr<T>` objects hold an equal `Status` or an
// equal instance of `T`. This function requires that `T` supports equality.
template <typename T>
bool operator==(StatusOr<T> const& a, StatusOr<T> const& b) {
if (!a || !b) return a.status() == b.status();
return *a == *b;
}
// Returns true of `a` and `b` are not equal. See `operator==` docs above for
// the definition of equal.
template <typename T>
bool operator!=(StatusOr<T> const& a, StatusOr<T> const& b) {
return !(a == b);
}
template <typename T>
StatusOr<T> make_status_or(T rhs) {
return StatusOr<T>(std::move(rhs));
}
} // namespace GOOGLE_CLOUD_CPP_NS
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STATUS_OR_H