statusor.h 27 KB

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