statusor.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. // Copyright 2020 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // File: statusor.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // An `absl::StatusOr<T>` represents a union of an `absl::Status` object
  20. // and an object of type `T`. The `absl::StatusOr<T>` will either contain an
  21. // object of type `T` (indicating a successful operation), or an error (of type
  22. // `absl::Status`) explaining why such a value is not present.
  23. //
  24. // In general, check the success of an operation returning an
  25. // `absl::StatusOr<T>` like you would an `absl::Status` by using the `ok()`
  26. // member function.
  27. //
  28. // Example:
  29. //
  30. // StatusOr<Foo> result = Calculation();
  31. // if (result.ok()) {
  32. // result->DoSomethingCool();
  33. // } else {
  34. // LOG(ERROR) << result.status();
  35. // }
  36. #ifndef ABSL_STATUS_STATUSOR_H_
  37. #define ABSL_STATUS_STATUSOR_H_
  38. #include <exception>
  39. #include <initializer_list>
  40. #include <new>
  41. #include <ostream>
  42. #include <string>
  43. #include <type_traits>
  44. #include <utility>
  45. #include "absl/base/attributes.h"
  46. #include "absl/base/nullability.h"
  47. #include "absl/base/call_once.h"
  48. #include "absl/meta/type_traits.h"
  49. #include "absl/status/internal/statusor_internal.h"
  50. #include "absl/status/status.h"
  51. #include "absl/strings/has_absl_stringify.h"
  52. #include "absl/strings/has_ostream_operator.h"
  53. #include "absl/strings/str_format.h"
  54. #include "absl/types/variant.h"
  55. #include "absl/utility/utility.h"
  56. namespace absl {
  57. ABSL_NAMESPACE_BEGIN
  58. // BadStatusOrAccess
  59. //
  60. // This class defines the type of object to throw (if exceptions are enabled),
  61. // when accessing the value of an `absl::StatusOr<T>` object that does not
  62. // contain a value. This behavior is analogous to that of
  63. // `std::bad_optional_access` in the case of accessing an invalid
  64. // `std::optional` value.
  65. //
  66. // Example:
  67. //
  68. // try {
  69. // absl::StatusOr<int> v = FetchInt();
  70. // DoWork(v.value()); // Accessing value() when not "OK" may throw
  71. // } catch (absl::BadStatusOrAccess& ex) {
  72. // LOG(ERROR) << ex.status();
  73. // }
  74. class BadStatusOrAccess : public std::exception {
  75. public:
  76. explicit BadStatusOrAccess(absl::Status status);
  77. ~BadStatusOrAccess() override = default;
  78. BadStatusOrAccess(const BadStatusOrAccess& other);
  79. BadStatusOrAccess& operator=(const BadStatusOrAccess& other);
  80. BadStatusOrAccess(BadStatusOrAccess&& other);
  81. BadStatusOrAccess& operator=(BadStatusOrAccess&& other);
  82. // BadStatusOrAccess::what()
  83. //
  84. // Returns the associated explanatory string of the `absl::StatusOr<T>`
  85. // object's error code. This function contains information about the failing
  86. // status, but its exact formatting may change and should not be depended on.
  87. //
  88. // The pointer of this string is guaranteed to be valid until any non-const
  89. // function is invoked on the exception object.
  90. absl::Nonnull<const char*> what() const noexcept override;
  91. // BadStatusOrAccess::status()
  92. //
  93. // Returns the associated `absl::Status` of the `absl::StatusOr<T>` object's
  94. // error.
  95. const absl::Status& status() const;
  96. private:
  97. void InitWhat() const;
  98. absl::Status status_;
  99. mutable absl::once_flag init_what_;
  100. mutable std::string what_;
  101. };
  102. // Returned StatusOr objects may not be ignored.
  103. template <typename T>
  104. #if ABSL_HAVE_CPP_ATTRIBUTE(nodiscard)
  105. // TODO(b/176172494): ABSL_MUST_USE_RESULT should expand to the more strict
  106. // [[nodiscard]]. For now, just use [[nodiscard]] directly when it is available.
  107. class [[nodiscard]] StatusOr;
  108. #else
  109. class ABSL_MUST_USE_RESULT StatusOr;
  110. #endif // ABSL_HAVE_CPP_ATTRIBUTE(nodiscard)
  111. // absl::StatusOr<T>
  112. //
  113. // The `absl::StatusOr<T>` class template is a union of an `absl::Status` object
  114. // and an object of type `T`. The `absl::StatusOr<T>` models an object that is
  115. // either a usable object, or an error (of type `absl::Status`) explaining why
  116. // such an object is not present. An `absl::StatusOr<T>` is typically the return
  117. // value of a function which may fail.
  118. //
  119. // An `absl::StatusOr<T>` can never hold an "OK" status (an
  120. // `absl::StatusCode::kOk` value); instead, the presence of an object of type
  121. // `T` indicates success. Instead of checking for a `kOk` value, use the
  122. // `absl::StatusOr<T>::ok()` member function. (It is for this reason, and code
  123. // readability, that using the `ok()` function is preferred for `absl::Status`
  124. // as well.)
  125. //
  126. // Example:
  127. //
  128. // StatusOr<Foo> result = DoBigCalculationThatCouldFail();
  129. // if (result.ok()) {
  130. // result->DoSomethingCool();
  131. // } else {
  132. // LOG(ERROR) << result.status();
  133. // }
  134. //
  135. // Accessing the object held by an `absl::StatusOr<T>` should be performed via
  136. // `operator*` or `operator->`, after a call to `ok()` confirms that the
  137. // `absl::StatusOr<T>` holds an object of type `T`:
  138. //
  139. // Example:
  140. //
  141. // absl::StatusOr<int> i = GetCount();
  142. // if (i.ok()) {
  143. // updated_total += *i;
  144. // }
  145. //
  146. // NOTE: using `absl::StatusOr<T>::value()` when no valid value is present will
  147. // throw an exception if exceptions are enabled or terminate the process when
  148. // exceptions are not enabled.
  149. //
  150. // Example:
  151. //
  152. // StatusOr<Foo> result = DoBigCalculationThatCouldFail();
  153. // const Foo& foo = result.value(); // Crash/exception if no value present
  154. // foo.DoSomethingCool();
  155. //
  156. // A `absl::StatusOr<T*>` can be constructed from a null pointer like any other
  157. // pointer value, and the result will be that `ok()` returns `true` and
  158. // `value()` returns `nullptr`. Checking the value of pointer in an
  159. // `absl::StatusOr<T*>` generally requires a bit more care, to ensure both that
  160. // a value is present and that value is not null:
  161. //
  162. // StatusOr<std::unique_ptr<Foo>> result = FooFactory::MakeNewFoo(arg);
  163. // if (!result.ok()) {
  164. // LOG(ERROR) << result.status();
  165. // } else if (*result == nullptr) {
  166. // LOG(ERROR) << "Unexpected null pointer";
  167. // } else {
  168. // (*result)->DoSomethingCool();
  169. // }
  170. //
  171. // Example factory implementation returning StatusOr<T>:
  172. //
  173. // StatusOr<Foo> FooFactory::MakeFoo(int arg) {
  174. // if (arg <= 0) {
  175. // return absl::Status(absl::StatusCode::kInvalidArgument,
  176. // "Arg must be positive");
  177. // }
  178. // return Foo(arg);
  179. // }
  180. template <typename T>
  181. class StatusOr : private internal_statusor::StatusOrData<T>,
  182. private internal_statusor::CopyCtorBase<T>,
  183. private internal_statusor::MoveCtorBase<T>,
  184. private internal_statusor::CopyAssignBase<T>,
  185. private internal_statusor::MoveAssignBase<T> {
  186. template <typename U>
  187. friend class StatusOr;
  188. typedef internal_statusor::StatusOrData<T> Base;
  189. public:
  190. // StatusOr<T>::value_type
  191. //
  192. // This instance data provides a generic `value_type` member for use within
  193. // generic programming. This usage is analogous to that of
  194. // `optional::value_type` in the case of `std::optional`.
  195. typedef T value_type;
  196. // Constructors
  197. // Constructs a new `absl::StatusOr` with an `absl::StatusCode::kUnknown`
  198. // status. This constructor is marked 'explicit' to prevent usages in return
  199. // values such as 'return {};', under the misconception that
  200. // `absl::StatusOr<std::vector<int>>` will be initialized with an empty
  201. // vector, instead of an `absl::StatusCode::kUnknown` error code.
  202. explicit StatusOr();
  203. // `StatusOr<T>` is copy constructible if `T` is copy constructible.
  204. StatusOr(const StatusOr&) = default;
  205. // `StatusOr<T>` is copy assignable if `T` is copy constructible and copy
  206. // assignable.
  207. StatusOr& operator=(const StatusOr&) = default;
  208. // `StatusOr<T>` is move constructible if `T` is move constructible.
  209. StatusOr(StatusOr&&) = default;
  210. // `StatusOr<T>` is moveAssignable if `T` is move constructible and move
  211. // assignable.
  212. StatusOr& operator=(StatusOr&&) = default;
  213. // Converting Constructors
  214. // Constructs a new `absl::StatusOr<T>` from an `absl::StatusOr<U>`, when `T`
  215. // is constructible from `U`. To avoid ambiguity, these constructors are
  216. // disabled if `T` is also constructible from `StatusOr<U>.`. This constructor
  217. // is explicit if and only if the corresponding construction of `T` from `U`
  218. // is explicit. (This constructor inherits its explicitness from the
  219. // underlying constructor.)
  220. template <typename U, absl::enable_if_t<
  221. internal_statusor::IsConstructionFromStatusOrValid<
  222. false, T, U, false, const U&>::value,
  223. int> = 0>
  224. StatusOr(const StatusOr<U>& other) // NOLINT
  225. : Base(static_cast<const typename StatusOr<U>::Base&>(other)) {}
  226. template <typename U, absl::enable_if_t<
  227. internal_statusor::IsConstructionFromStatusOrValid<
  228. false, T, U, true, const U&>::value,
  229. int> = 0>
  230. StatusOr(const StatusOr<U>& other ABSL_ATTRIBUTE_LIFETIME_BOUND) // NOLINT
  231. : Base(static_cast<const typename StatusOr<U>::Base&>(other)) {}
  232. template <typename U, absl::enable_if_t<
  233. internal_statusor::IsConstructionFromStatusOrValid<
  234. true, T, U, false, const U&>::value,
  235. int> = 0>
  236. explicit StatusOr(const StatusOr<U>& other)
  237. : Base(static_cast<const typename StatusOr<U>::Base&>(other)) {}
  238. template <typename U, absl::enable_if_t<
  239. internal_statusor::IsConstructionFromStatusOrValid<
  240. true, T, U, true, const U&>::value,
  241. int> = 0>
  242. explicit StatusOr(const StatusOr<U>& other ABSL_ATTRIBUTE_LIFETIME_BOUND)
  243. : Base(static_cast<const typename StatusOr<U>::Base&>(other)) {}
  244. template <typename U, absl::enable_if_t<
  245. internal_statusor::IsConstructionFromStatusOrValid<
  246. false, T, U, false, U&&>::value,
  247. int> = 0>
  248. StatusOr(StatusOr<U>&& other) // NOLINT
  249. : Base(static_cast<typename StatusOr<U>::Base&&>(other)) {}
  250. template <typename U, absl::enable_if_t<
  251. internal_statusor::IsConstructionFromStatusOrValid<
  252. false, T, U, true, U&&>::value,
  253. int> = 0>
  254. StatusOr(StatusOr<U>&& other ABSL_ATTRIBUTE_LIFETIME_BOUND) // NOLINT
  255. : Base(static_cast<typename StatusOr<U>::Base&&>(other)) {}
  256. template <typename U, absl::enable_if_t<
  257. internal_statusor::IsConstructionFromStatusOrValid<
  258. true, T, U, false, U&&>::value,
  259. int> = 0>
  260. explicit StatusOr(StatusOr<U>&& other)
  261. : Base(static_cast<typename StatusOr<U>::Base&&>(other)) {}
  262. template <typename U, absl::enable_if_t<
  263. internal_statusor::IsConstructionFromStatusOrValid<
  264. true, T, U, true, U&&>::value,
  265. int> = 0>
  266. explicit StatusOr(StatusOr<U>&& other ABSL_ATTRIBUTE_LIFETIME_BOUND)
  267. : Base(static_cast<typename StatusOr<U>::Base&&>(other)) {}
  268. // Converting Assignment Operators
  269. // Creates an `absl::StatusOr<T>` through assignment from an
  270. // `absl::StatusOr<U>` when:
  271. //
  272. // * Both `absl::StatusOr<T>` and `absl::StatusOr<U>` are OK by assigning
  273. // `U` to `T` directly.
  274. // * `absl::StatusOr<T>` is OK and `absl::StatusOr<U>` contains an error
  275. // code by destroying `absl::StatusOr<T>`'s value and assigning from
  276. // `absl::StatusOr<U>'
  277. // * `absl::StatusOr<T>` contains an error code and `absl::StatusOr<U>` is
  278. // OK by directly initializing `T` from `U`.
  279. // * Both `absl::StatusOr<T>` and `absl::StatusOr<U>` contain an error
  280. // code by assigning the `Status` in `absl::StatusOr<U>` to
  281. // `absl::StatusOr<T>`
  282. //
  283. // These overloads only apply if `absl::StatusOr<T>` is constructible and
  284. // assignable from `absl::StatusOr<U>` and `StatusOr<T>` cannot be directly
  285. // assigned from `StatusOr<U>`.
  286. template <typename U,
  287. absl::enable_if_t<internal_statusor::IsStatusOrAssignmentValid<
  288. T, const U&, false>::value,
  289. int> = 0>
  290. StatusOr& operator=(const StatusOr<U>& other) {
  291. this->Assign(other);
  292. return *this;
  293. }
  294. template <typename U,
  295. absl::enable_if_t<internal_statusor::IsStatusOrAssignmentValid<
  296. T, const U&, true>::value,
  297. int> = 0>
  298. StatusOr& operator=(const StatusOr<U>& other ABSL_ATTRIBUTE_LIFETIME_BOUND) {
  299. this->Assign(other);
  300. return *this;
  301. }
  302. template <typename U,
  303. absl::enable_if_t<internal_statusor::IsStatusOrAssignmentValid<
  304. T, U&&, false>::value,
  305. int> = 0>
  306. StatusOr& operator=(StatusOr<U>&& other) {
  307. this->Assign(std::move(other));
  308. return *this;
  309. }
  310. template <typename U,
  311. absl::enable_if_t<internal_statusor::IsStatusOrAssignmentValid<
  312. T, U&&, true>::value,
  313. int> = 0>
  314. StatusOr& operator=(StatusOr<U>&& other ABSL_ATTRIBUTE_LIFETIME_BOUND) {
  315. this->Assign(std::move(other));
  316. return *this;
  317. }
  318. // Constructs a new `absl::StatusOr<T>` with a non-ok status. After calling
  319. // this constructor, `this->ok()` will be `false` and calls to `value()` will
  320. // crash, or produce an exception if exceptions are enabled.
  321. //
  322. // The constructor also takes any type `U` that is convertible to
  323. // `absl::Status`. This constructor is explicit if an only if `U` is not of
  324. // type `absl::Status` and the conversion from `U` to `Status` is explicit.
  325. //
  326. // REQUIRES: !Status(std::forward<U>(v)).ok(). This requirement is DCHECKed.
  327. // In optimized builds, passing absl::OkStatus() here will have the effect
  328. // of passing absl::StatusCode::kInternal as a fallback.
  329. template <typename U = absl::Status,
  330. absl::enable_if_t<internal_statusor::IsConstructionFromStatusValid<
  331. false, T, U>::value,
  332. int> = 0>
  333. StatusOr(U&& v) : Base(std::forward<U>(v)) {}
  334. template <typename U = absl::Status,
  335. absl::enable_if_t<internal_statusor::IsConstructionFromStatusValid<
  336. true, T, U>::value,
  337. int> = 0>
  338. explicit StatusOr(U&& v) : Base(std::forward<U>(v)) {}
  339. template <typename U = absl::Status,
  340. absl::enable_if_t<internal_statusor::IsConstructionFromStatusValid<
  341. false, T, U>::value,
  342. int> = 0>
  343. StatusOr& operator=(U&& v) {
  344. this->AssignStatus(std::forward<U>(v));
  345. return *this;
  346. }
  347. // Perfect-forwarding value assignment operator.
  348. // If `*this` contains a `T` value before the call, the contained value is
  349. // assigned from `std::forward<U>(v)`; Otherwise, it is directly-initialized
  350. // from `std::forward<U>(v)`.
  351. // This function does not participate in overload unless:
  352. // 1. `std::is_constructible_v<T, U>` is true,
  353. // 2. `std::is_assignable_v<T&, U>` is true.
  354. // 3. `std::is_same_v<StatusOr<T>, std::remove_cvref_t<U>>` is false.
  355. // 4. Assigning `U` to `T` is not ambiguous:
  356. // If `U` is `StatusOr<V>` and `T` is constructible and assignable from
  357. // both `StatusOr<V>` and `V`, the assignment is considered bug-prone and
  358. // ambiguous thus will fail to compile. For example:
  359. // StatusOr<bool> s1 = true; // s1.ok() && *s1 == true
  360. // StatusOr<bool> s2 = false; // s2.ok() && *s2 == false
  361. // s1 = s2; // ambiguous, `s1 = *s2` or `s1 = bool(s2)`?
  362. template <typename U = T,
  363. typename std::enable_if<
  364. internal_statusor::IsAssignmentValid<T, U, false>::value,
  365. int>::type = 0>
  366. StatusOr& operator=(U&& v) {
  367. this->Assign(std::forward<U>(v));
  368. return *this;
  369. }
  370. template <typename U = T,
  371. typename std::enable_if<
  372. internal_statusor::IsAssignmentValid<T, U, true>::value,
  373. int>::type = 0>
  374. StatusOr& operator=(U&& v ABSL_ATTRIBUTE_LIFETIME_BOUND) {
  375. this->Assign(std::forward<U>(v));
  376. return *this;
  377. }
  378. // Constructs the inner value `T` in-place using the provided args, using the
  379. // `T(args...)` constructor.
  380. template <typename... Args>
  381. explicit StatusOr(absl::in_place_t, Args&&... args);
  382. template <typename U, typename... Args>
  383. explicit StatusOr(absl::in_place_t, std::initializer_list<U> ilist,
  384. Args&&... args);
  385. // Constructs the inner value `T` in-place using the provided args, using the
  386. // `T(U)` (direct-initialization) constructor. This constructor is only valid
  387. // if `T` can be constructed from a `U`. Can accept move or copy constructors.
  388. //
  389. // This constructor is explicit if `U` is not convertible to `T`. To avoid
  390. // ambiguity, this constructor is disabled if `U` is a `StatusOr<J>`, where
  391. // `J` is convertible to `T`.
  392. template <typename U = T,
  393. absl::enable_if_t<internal_statusor::IsConstructionValid<
  394. false, T, U, false>::value,
  395. int> = 0>
  396. StatusOr(U&& u) // NOLINT
  397. : StatusOr(absl::in_place, std::forward<U>(u)) {}
  398. template <typename U = T,
  399. absl::enable_if_t<internal_statusor::IsConstructionValid<
  400. false, T, U, true>::value,
  401. int> = 0>
  402. StatusOr(U&& u ABSL_ATTRIBUTE_LIFETIME_BOUND) // NOLINT
  403. : StatusOr(absl::in_place, std::forward<U>(u)) {}
  404. template <typename U = T,
  405. absl::enable_if_t<internal_statusor::IsConstructionValid<
  406. true, T, U, false>::value,
  407. int> = 0>
  408. explicit StatusOr(U&& u) // NOLINT
  409. : StatusOr(absl::in_place, std::forward<U>(u)) {}
  410. template <typename U = T,
  411. absl::enable_if_t<
  412. internal_statusor::IsConstructionValid<true, T, U, true>::value,
  413. int> = 0>
  414. explicit StatusOr(U&& u ABSL_ATTRIBUTE_LIFETIME_BOUND) // NOLINT
  415. : StatusOr(absl::in_place, std::forward<U>(u)) {}
  416. // StatusOr<T>::ok()
  417. //
  418. // Returns whether or not this `absl::StatusOr<T>` holds a `T` value. This
  419. // member function is analogous to `absl::Status::ok()` and should be used
  420. // similarly to check the status of return values.
  421. //
  422. // Example:
  423. //
  424. // StatusOr<Foo> result = DoBigCalculationThatCouldFail();
  425. // if (result.ok()) {
  426. // // Handle result
  427. // else {
  428. // // Handle error
  429. // }
  430. ABSL_MUST_USE_RESULT bool ok() const { return this->status_.ok(); }
  431. // StatusOr<T>::status()
  432. //
  433. // Returns a reference to the current `absl::Status` contained within the
  434. // `absl::StatusOr<T>`. If `absl::StatusOr<T>` contains a `T`, then this
  435. // function returns `absl::OkStatus()`.
  436. const Status& status() const&;
  437. Status status() &&;
  438. // StatusOr<T>::value()
  439. //
  440. // Returns a reference to the held value if `this->ok()`. Otherwise, throws
  441. // `absl::BadStatusOrAccess` if exceptions are enabled, or is guaranteed to
  442. // terminate the process if exceptions are disabled.
  443. //
  444. // If you have already checked the status using `this->ok()`, you probably
  445. // want to use `operator*()` or `operator->()` to access the value instead of
  446. // `value`.
  447. //
  448. // Note: for value types that are cheap to copy, prefer simple code:
  449. //
  450. // T value = statusor.value();
  451. //
  452. // Otherwise, if the value type is expensive to copy, but can be left
  453. // in the StatusOr, simply assign to a reference:
  454. //
  455. // T& value = statusor.value(); // or `const T&`
  456. //
  457. // Otherwise, if the value type supports an efficient move, it can be
  458. // used as follows:
  459. //
  460. // T value = std::move(statusor).value();
  461. //
  462. // The `std::move` on statusor instead of on the whole expression enables
  463. // warnings about possible uses of the statusor object after the move.
  464. const T& value() const& ABSL_ATTRIBUTE_LIFETIME_BOUND;
  465. T& value() & ABSL_ATTRIBUTE_LIFETIME_BOUND;
  466. const T&& value() const&& ABSL_ATTRIBUTE_LIFETIME_BOUND;
  467. T&& value() && ABSL_ATTRIBUTE_LIFETIME_BOUND;
  468. // StatusOr<T>:: operator*()
  469. //
  470. // Returns a reference to the current value.
  471. //
  472. // REQUIRES: `this->ok() == true`, otherwise the behavior is undefined.
  473. //
  474. // Use `this->ok()` to verify that there is a current value within the
  475. // `absl::StatusOr<T>`. Alternatively, see the `value()` member function for a
  476. // similar API that guarantees crashing or throwing an exception if there is
  477. // no current value.
  478. const T& operator*() const& ABSL_ATTRIBUTE_LIFETIME_BOUND;
  479. T& operator*() & ABSL_ATTRIBUTE_LIFETIME_BOUND;
  480. const T&& operator*() const&& ABSL_ATTRIBUTE_LIFETIME_BOUND;
  481. T&& operator*() && ABSL_ATTRIBUTE_LIFETIME_BOUND;
  482. // StatusOr<T>::operator->()
  483. //
  484. // Returns a pointer to the current value.
  485. //
  486. // REQUIRES: `this->ok() == true`, otherwise the behavior is undefined.
  487. //
  488. // Use `this->ok()` to verify that there is a current value.
  489. const T* operator->() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  490. T* operator->() ABSL_ATTRIBUTE_LIFETIME_BOUND;
  491. // StatusOr<T>::value_or()
  492. //
  493. // Returns the current value if `this->ok() == true`. Otherwise constructs a
  494. // value using the provided `default_value`.
  495. //
  496. // Unlike `value`, this function returns by value, copying the current value
  497. // if necessary. If the value type supports an efficient move, it can be used
  498. // as follows:
  499. //
  500. // T value = std::move(statusor).value_or(def);
  501. //
  502. // Unlike with `value`, calling `std::move()` on the result of `value_or` will
  503. // still trigger a copy.
  504. template <typename U>
  505. T value_or(U&& default_value) const&;
  506. template <typename U>
  507. T value_or(U&& default_value) &&;
  508. // StatusOr<T>::IgnoreError()
  509. //
  510. // Ignores any errors. This method does nothing except potentially suppress
  511. // complaints from any tools that are checking that errors are not dropped on
  512. // the floor.
  513. void IgnoreError() const;
  514. // StatusOr<T>::emplace()
  515. //
  516. // Reconstructs the inner value T in-place using the provided args, using the
  517. // T(args...) constructor. Returns reference to the reconstructed `T`.
  518. template <typename... Args>
  519. T& emplace(Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  520. if (ok()) {
  521. this->Clear();
  522. this->MakeValue(std::forward<Args>(args)...);
  523. } else {
  524. this->MakeValue(std::forward<Args>(args)...);
  525. this->status_ = absl::OkStatus();
  526. }
  527. return this->data_;
  528. }
  529. template <
  530. typename U, typename... Args,
  531. absl::enable_if_t<
  532. std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value,
  533. int> = 0>
  534. T& emplace(std::initializer_list<U> ilist,
  535. Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  536. if (ok()) {
  537. this->Clear();
  538. this->MakeValue(ilist, std::forward<Args>(args)...);
  539. } else {
  540. this->MakeValue(ilist, std::forward<Args>(args)...);
  541. this->status_ = absl::OkStatus();
  542. }
  543. return this->data_;
  544. }
  545. // StatusOr<T>::AssignStatus()
  546. //
  547. // Sets the status of `absl::StatusOr<T>` to the given non-ok status value.
  548. //
  549. // NOTE: We recommend using the constructor and `operator=` where possible.
  550. // This method is intended for use in generic programming, to enable setting
  551. // the status of a `StatusOr<T>` when `T` may be `Status`. In that case, the
  552. // constructor and `operator=` would assign into the inner value of type
  553. // `Status`, rather than status of the `StatusOr` (b/280392796).
  554. //
  555. // REQUIRES: !Status(std::forward<U>(v)).ok(). This requirement is DCHECKed.
  556. // In optimized builds, passing absl::OkStatus() here will have the effect
  557. // of passing absl::StatusCode::kInternal as a fallback.
  558. using internal_statusor::StatusOrData<T>::AssignStatus;
  559. private:
  560. using internal_statusor::StatusOrData<T>::Assign;
  561. template <typename U>
  562. void Assign(const absl::StatusOr<U>& other);
  563. template <typename U>
  564. void Assign(absl::StatusOr<U>&& other);
  565. };
  566. // operator==()
  567. //
  568. // This operator checks the equality of two `absl::StatusOr<T>` objects.
  569. template <typename T>
  570. bool operator==(const StatusOr<T>& lhs, const StatusOr<T>& rhs) {
  571. if (lhs.ok() && rhs.ok()) return *lhs == *rhs;
  572. return lhs.status() == rhs.status();
  573. }
  574. // operator!=()
  575. //
  576. // This operator checks the inequality of two `absl::StatusOr<T>` objects.
  577. template <typename T>
  578. bool operator!=(const StatusOr<T>& lhs, const StatusOr<T>& rhs) {
  579. return !(lhs == rhs);
  580. }
  581. // Prints the `value` or the status in brackets to `os`.
  582. //
  583. // Requires `T` supports `operator<<`. Do not rely on the output format which
  584. // may change without notice.
  585. template <typename T, typename std::enable_if<
  586. absl::HasOstreamOperator<T>::value, int>::type = 0>
  587. std::ostream& operator<<(std::ostream& os, const StatusOr<T>& status_or) {
  588. if (status_or.ok()) {
  589. os << status_or.value();
  590. } else {
  591. os << internal_statusor::StringifyRandom::OpenBrackets()
  592. << status_or.status()
  593. << internal_statusor::StringifyRandom::CloseBrackets();
  594. }
  595. return os;
  596. }
  597. // As above, but supports `StrCat`, `StrFormat`, etc.
  598. //
  599. // Requires `T` has `AbslStringify`. Do not rely on the output format which
  600. // may change without notice.
  601. template <
  602. typename Sink, typename T,
  603. typename std::enable_if<absl::HasAbslStringify<T>::value, int>::type = 0>
  604. void AbslStringify(Sink& sink, const StatusOr<T>& status_or) {
  605. if (status_or.ok()) {
  606. absl::Format(&sink, "%v", status_or.value());
  607. } else {
  608. absl::Format(&sink, "%s%v%s",
  609. internal_statusor::StringifyRandom::OpenBrackets(),
  610. status_or.status(),
  611. internal_statusor::StringifyRandom::CloseBrackets());
  612. }
  613. }
  614. //------------------------------------------------------------------------------
  615. // Implementation details for StatusOr<T>
  616. //------------------------------------------------------------------------------
  617. // TODO(sbenza): avoid the string here completely.
  618. template <typename T>
  619. StatusOr<T>::StatusOr() : Base(Status(absl::StatusCode::kUnknown, "")) {}
  620. template <typename T>
  621. template <typename U>
  622. inline void StatusOr<T>::Assign(const StatusOr<U>& other) {
  623. if (other.ok()) {
  624. this->Assign(*other);
  625. } else {
  626. this->AssignStatus(other.status());
  627. }
  628. }
  629. template <typename T>
  630. template <typename U>
  631. inline void StatusOr<T>::Assign(StatusOr<U>&& other) {
  632. if (other.ok()) {
  633. this->Assign(*std::move(other));
  634. } else {
  635. this->AssignStatus(std::move(other).status());
  636. }
  637. }
  638. template <typename T>
  639. template <typename... Args>
  640. StatusOr<T>::StatusOr(absl::in_place_t, Args&&... args)
  641. : Base(absl::in_place, std::forward<Args>(args)...) {}
  642. template <typename T>
  643. template <typename U, typename... Args>
  644. StatusOr<T>::StatusOr(absl::in_place_t, std::initializer_list<U> ilist,
  645. Args&&... args)
  646. : Base(absl::in_place, ilist, std::forward<Args>(args)...) {}
  647. template <typename T>
  648. const Status& StatusOr<T>::status() const& {
  649. return this->status_;
  650. }
  651. template <typename T>
  652. Status StatusOr<T>::status() && {
  653. return ok() ? OkStatus() : std::move(this->status_);
  654. }
  655. template <typename T>
  656. const T& StatusOr<T>::value() const& {
  657. if (!this->ok()) internal_statusor::ThrowBadStatusOrAccess(this->status_);
  658. return this->data_;
  659. }
  660. template <typename T>
  661. T& StatusOr<T>::value() & {
  662. if (!this->ok()) internal_statusor::ThrowBadStatusOrAccess(this->status_);
  663. return this->data_;
  664. }
  665. template <typename T>
  666. const T&& StatusOr<T>::value() const&& {
  667. if (!this->ok()) {
  668. internal_statusor::ThrowBadStatusOrAccess(std::move(this->status_));
  669. }
  670. return std::move(this->data_);
  671. }
  672. template <typename T>
  673. T&& StatusOr<T>::value() && {
  674. if (!this->ok()) {
  675. internal_statusor::ThrowBadStatusOrAccess(std::move(this->status_));
  676. }
  677. return std::move(this->data_);
  678. }
  679. template <typename T>
  680. const T& StatusOr<T>::operator*() const& {
  681. this->EnsureOk();
  682. return this->data_;
  683. }
  684. template <typename T>
  685. T& StatusOr<T>::operator*() & {
  686. this->EnsureOk();
  687. return this->data_;
  688. }
  689. template <typename T>
  690. const T&& StatusOr<T>::operator*() const&& {
  691. this->EnsureOk();
  692. return std::move(this->data_);
  693. }
  694. template <typename T>
  695. T&& StatusOr<T>::operator*() && {
  696. this->EnsureOk();
  697. return std::move(this->data_);
  698. }
  699. template <typename T>
  700. absl::Nonnull<const T*> StatusOr<T>::operator->() const {
  701. this->EnsureOk();
  702. return &this->data_;
  703. }
  704. template <typename T>
  705. absl::Nonnull<T*> StatusOr<T>::operator->() {
  706. this->EnsureOk();
  707. return &this->data_;
  708. }
  709. template <typename T>
  710. template <typename U>
  711. T StatusOr<T>::value_or(U&& default_value) const& {
  712. if (ok()) {
  713. return this->data_;
  714. }
  715. return std::forward<U>(default_value);
  716. }
  717. template <typename T>
  718. template <typename U>
  719. T StatusOr<T>::value_or(U&& default_value) && {
  720. if (ok()) {
  721. return std::move(this->data_);
  722. }
  723. return std::forward<U>(default_value);
  724. }
  725. template <typename T>
  726. void StatusOr<T>::IgnoreError() const {
  727. // no-op
  728. }
  729. ABSL_NAMESPACE_END
  730. } // namespace absl
  731. #endif // ABSL_STATUS_STATUSOR_H_