statusor.h 26 KB

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