statusor.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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 <
  221. typename U,
  222. absl::enable_if_t<
  223. absl::conjunction<
  224. absl::negation<std::is_same<T, U>>,
  225. std::is_constructible<T, const U&>,
  226. std::is_convertible<const U&, T>,
  227. absl::negation<
  228. internal_statusor::IsConstructibleOrConvertibleFromStatusOr<
  229. T, U>>>::value,
  230. int> = 0>
  231. StatusOr(const StatusOr<U>& other) // NOLINT
  232. : Base(static_cast<const typename StatusOr<U>::Base&>(other)) {}
  233. template <
  234. typename U,
  235. absl::enable_if_t<
  236. absl::conjunction<
  237. absl::negation<std::is_same<T, U>>,
  238. std::is_constructible<T, const U&>,
  239. absl::negation<std::is_convertible<const U&, T>>,
  240. absl::negation<
  241. internal_statusor::IsConstructibleOrConvertibleFromStatusOr<
  242. T, U>>>::value,
  243. int> = 0>
  244. explicit StatusOr(const StatusOr<U>& other)
  245. : Base(static_cast<const typename StatusOr<U>::Base&>(other)) {}
  246. template <
  247. typename U,
  248. absl::enable_if_t<
  249. absl::conjunction<
  250. absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>,
  251. std::is_convertible<U&&, T>,
  252. absl::negation<
  253. internal_statusor::IsConstructibleOrConvertibleFromStatusOr<
  254. T, U>>>::value,
  255. int> = 0>
  256. StatusOr(StatusOr<U>&& other) // NOLINT
  257. : Base(static_cast<typename StatusOr<U>::Base&&>(other)) {}
  258. template <
  259. typename U,
  260. absl::enable_if_t<
  261. absl::conjunction<
  262. absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>,
  263. absl::negation<std::is_convertible<U&&, T>>,
  264. absl::negation<
  265. internal_statusor::IsConstructibleOrConvertibleFromStatusOr<
  266. T, U>>>::value,
  267. int> = 0>
  268. explicit StatusOr(StatusOr<U>&& other)
  269. : Base(static_cast<typename StatusOr<U>::Base&&>(other)) {}
  270. // Converting Assignment Operators
  271. // Creates an `absl::StatusOr<T>` through assignment from an
  272. // `absl::StatusOr<U>` when:
  273. //
  274. // * Both `absl::StatusOr<T>` and `absl::StatusOr<U>` are OK by assigning
  275. // `U` to `T` directly.
  276. // * `absl::StatusOr<T>` is OK and `absl::StatusOr<U>` contains an error
  277. // code by destroying `absl::StatusOr<T>`'s value and assigning from
  278. // `absl::StatusOr<U>'
  279. // * `absl::StatusOr<T>` contains an error code and `absl::StatusOr<U>` is
  280. // OK by directly initializing `T` from `U`.
  281. // * Both `absl::StatusOr<T>` and `absl::StatusOr<U>` contain an error
  282. // code by assigning the `Status` in `absl::StatusOr<U>` to
  283. // `absl::StatusOr<T>`
  284. //
  285. // These overloads only apply if `absl::StatusOr<T>` is constructible and
  286. // assignable from `absl::StatusOr<U>` and `StatusOr<T>` cannot be directly
  287. // assigned from `StatusOr<U>`.
  288. template <
  289. typename U,
  290. absl::enable_if_t<
  291. absl::conjunction<
  292. absl::negation<std::is_same<T, U>>,
  293. std::is_constructible<T, const U&>,
  294. std::is_assignable<T, const U&>,
  295. absl::negation<
  296. internal_statusor::
  297. IsConstructibleOrConvertibleOrAssignableFromStatusOr<
  298. T, U>>>::value,
  299. int> = 0>
  300. StatusOr& operator=(const StatusOr<U>& other) {
  301. this->Assign(other);
  302. return *this;
  303. }
  304. template <
  305. typename U,
  306. absl::enable_if_t<
  307. absl::conjunction<
  308. absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>,
  309. std::is_assignable<T, U&&>,
  310. absl::negation<
  311. internal_statusor::
  312. IsConstructibleOrConvertibleOrAssignableFromStatusOr<
  313. T, U>>>::value,
  314. int> = 0>
  315. StatusOr& operator=(StatusOr<U>&& other) {
  316. this->Assign(std::move(other));
  317. return *this;
  318. }
  319. // Constructs a new `absl::StatusOr<T>` with a non-ok status. After calling
  320. // this constructor, `this->ok()` will be `false` and calls to `value()` will
  321. // crash, or produce an exception if exceptions are enabled.
  322. //
  323. // The constructor also takes any type `U` that is convertible to
  324. // `absl::Status`. This constructor is explicit if an only if `U` is not of
  325. // type `absl::Status` and the conversion from `U` to `Status` is explicit.
  326. //
  327. // REQUIRES: !Status(std::forward<U>(v)).ok(). This requirement is DCHECKed.
  328. // In optimized builds, passing absl::OkStatus() here will have the effect
  329. // of passing absl::StatusCode::kInternal as a fallback.
  330. template <
  331. typename U = absl::Status,
  332. absl::enable_if_t<
  333. absl::conjunction<
  334. std::is_convertible<U&&, absl::Status>,
  335. std::is_constructible<absl::Status, U&&>,
  336. absl::negation<std::is_same<absl::decay_t<U>, absl::StatusOr<T>>>,
  337. absl::negation<std::is_same<absl::decay_t<U>, T>>,
  338. absl::negation<std::is_same<absl::decay_t<U>, absl::in_place_t>>,
  339. absl::negation<internal_statusor::HasConversionOperatorToStatusOr<
  340. T, U&&>>>::value,
  341. int> = 0>
  342. StatusOr(U&& v) : Base(std::forward<U>(v)) {}
  343. template <
  344. typename U = absl::Status,
  345. absl::enable_if_t<
  346. absl::conjunction<
  347. absl::negation<std::is_convertible<U&&, absl::Status>>,
  348. std::is_constructible<absl::Status, U&&>,
  349. absl::negation<std::is_same<absl::decay_t<U>, absl::StatusOr<T>>>,
  350. absl::negation<std::is_same<absl::decay_t<U>, T>>,
  351. absl::negation<std::is_same<absl::decay_t<U>, absl::in_place_t>>,
  352. absl::negation<internal_statusor::HasConversionOperatorToStatusOr<
  353. T, U&&>>>::value,
  354. int> = 0>
  355. explicit StatusOr(U&& v) : Base(std::forward<U>(v)) {}
  356. template <
  357. typename U = absl::Status,
  358. absl::enable_if_t<
  359. absl::conjunction<
  360. std::is_convertible<U&&, absl::Status>,
  361. std::is_constructible<absl::Status, U&&>,
  362. absl::negation<std::is_same<absl::decay_t<U>, absl::StatusOr<T>>>,
  363. absl::negation<std::is_same<absl::decay_t<U>, T>>,
  364. absl::negation<std::is_same<absl::decay_t<U>, absl::in_place_t>>,
  365. absl::negation<internal_statusor::HasConversionOperatorToStatusOr<
  366. T, U&&>>>::value,
  367. int> = 0>
  368. StatusOr& operator=(U&& v) {
  369. this->AssignStatus(std::forward<U>(v));
  370. return *this;
  371. }
  372. // Perfect-forwarding value assignment operator.
  373. // If `*this` contains a `T` value before the call, the contained value is
  374. // assigned from `std::forward<U>(v)`; Otherwise, it is directly-initialized
  375. // from `std::forward<U>(v)`.
  376. // This function does not participate in overload unless:
  377. // 1. `std::is_constructible_v<T, U>` is true,
  378. // 2. `std::is_assignable_v<T&, U>` is true.
  379. // 3. `std::is_same_v<StatusOr<T>, std::remove_cvref_t<U>>` is false.
  380. // 4. Assigning `U` to `T` is not ambiguous:
  381. // If `U` is `StatusOr<V>` and `T` is constructible and assignable from
  382. // both `StatusOr<V>` and `V`, the assignment is considered bug-prone and
  383. // ambiguous thus will fail to compile. For example:
  384. // StatusOr<bool> s1 = true; // s1.ok() && *s1 == true
  385. // StatusOr<bool> s2 = false; // s2.ok() && *s2 == false
  386. // s1 = s2; // ambiguous, `s1 = *s2` or `s1 = bool(s2)`?
  387. template <
  388. typename U = T,
  389. typename = typename std::enable_if<absl::conjunction<
  390. std::is_constructible<T, U&&>, std::is_assignable<T&, U&&>,
  391. absl::disjunction<
  392. std::is_same<absl::remove_cvref_t<U>, T>,
  393. absl::conjunction<
  394. absl::negation<std::is_convertible<U&&, absl::Status>>,
  395. absl::negation<internal_statusor::
  396. HasConversionOperatorToStatusOr<T, U&&>>>>,
  397. internal_statusor::IsForwardingAssignmentValid<T, U&&>>::value>::type>
  398. StatusOr& operator=(U&& v) {
  399. this->Assign(std::forward<U>(v));
  400. return *this;
  401. }
  402. // Constructs the inner value `T` in-place using the provided args, using the
  403. // `T(args...)` constructor.
  404. template <typename... Args>
  405. explicit StatusOr(absl::in_place_t, Args&&... args);
  406. template <typename U, typename... Args>
  407. explicit StatusOr(absl::in_place_t, std::initializer_list<U> ilist,
  408. Args&&... args);
  409. // Constructs the inner value `T` in-place using the provided args, using the
  410. // `T(U)` (direct-initialization) constructor. This constructor is only valid
  411. // if `T` can be constructed from a `U`. Can accept move or copy constructors.
  412. //
  413. // This constructor is explicit if `U` is not convertible to `T`. To avoid
  414. // ambiguity, this constructor is disabled if `U` is a `StatusOr<J>`, where
  415. // `J` is convertible to `T`.
  416. template <
  417. typename U = T,
  418. absl::enable_if_t<
  419. absl::conjunction<
  420. internal_statusor::IsDirectInitializationValid<T, U&&>,
  421. std::is_constructible<T, U&&>, std::is_convertible<U&&, T>,
  422. absl::disjunction<
  423. std::is_same<absl::remove_cvref_t<U>, T>,
  424. absl::conjunction<
  425. absl::negation<std::is_convertible<U&&, absl::Status>>,
  426. absl::negation<
  427. internal_statusor::HasConversionOperatorToStatusOr<
  428. T, U&&>>>>>::value,
  429. int> = 0>
  430. StatusOr(U&& u) // NOLINT
  431. : StatusOr(absl::in_place, std::forward<U>(u)) {}
  432. template <
  433. typename U = T,
  434. absl::enable_if_t<
  435. absl::conjunction<
  436. internal_statusor::IsDirectInitializationValid<T, U&&>,
  437. absl::disjunction<
  438. std::is_same<absl::remove_cvref_t<U>, T>,
  439. absl::conjunction<
  440. absl::negation<std::is_constructible<absl::Status, U&&>>,
  441. absl::negation<
  442. internal_statusor::HasConversionOperatorToStatusOr<
  443. T, U&&>>>>,
  444. std::is_constructible<T, U&&>,
  445. absl::negation<std::is_convertible<U&&, T>>>::value,
  446. int> = 0>
  447. explicit StatusOr(U&& u) // NOLINT
  448. : StatusOr(absl::in_place, std::forward<U>(u)) {}
  449. // StatusOr<T>::ok()
  450. //
  451. // Returns whether or not this `absl::StatusOr<T>` holds a `T` value. This
  452. // member function is analogous to `absl::Status::ok()` and should be used
  453. // similarly to check the status of return values.
  454. //
  455. // Example:
  456. //
  457. // StatusOr<Foo> result = DoBigCalculationThatCouldFail();
  458. // if (result.ok()) {
  459. // // Handle result
  460. // else {
  461. // // Handle error
  462. // }
  463. ABSL_MUST_USE_RESULT bool ok() const { return this->status_.ok(); }
  464. // StatusOr<T>::status()
  465. //
  466. // Returns a reference to the current `absl::Status` contained within the
  467. // `absl::StatusOr<T>`. If `absl::StatusOr<T>` contains a `T`, then this
  468. // function returns `absl::OkStatus()`.
  469. const Status& status() const&;
  470. Status status() &&;
  471. // StatusOr<T>::value()
  472. //
  473. // Returns a reference to the held value if `this->ok()`. Otherwise, throws
  474. // `absl::BadStatusOrAccess` if exceptions are enabled, or is guaranteed to
  475. // terminate the process if exceptions are disabled.
  476. //
  477. // If you have already checked the status using `this->ok()`, you probably
  478. // want to use `operator*()` or `operator->()` to access the value instead of
  479. // `value`.
  480. //
  481. // Note: for value types that are cheap to copy, prefer simple code:
  482. //
  483. // T value = statusor.value();
  484. //
  485. // Otherwise, if the value type is expensive to copy, but can be left
  486. // in the StatusOr, simply assign to a reference:
  487. //
  488. // T& value = statusor.value(); // or `const T&`
  489. //
  490. // Otherwise, if the value type supports an efficient move, it can be
  491. // used as follows:
  492. //
  493. // T value = std::move(statusor).value();
  494. //
  495. // The `std::move` on statusor instead of on the whole expression enables
  496. // warnings about possible uses of the statusor object after the move.
  497. const T& value() const& ABSL_ATTRIBUTE_LIFETIME_BOUND;
  498. T& value() & ABSL_ATTRIBUTE_LIFETIME_BOUND;
  499. const T&& value() const&& ABSL_ATTRIBUTE_LIFETIME_BOUND;
  500. T&& value() && ABSL_ATTRIBUTE_LIFETIME_BOUND;
  501. // StatusOr<T>:: operator*()
  502. //
  503. // Returns a reference to the current value.
  504. //
  505. // REQUIRES: `this->ok() == true`, otherwise the behavior is undefined.
  506. //
  507. // Use `this->ok()` to verify that there is a current value within the
  508. // `absl::StatusOr<T>`. Alternatively, see the `value()` member function for a
  509. // similar API that guarantees crashing or throwing an exception if there is
  510. // no current value.
  511. const T& operator*() const& ABSL_ATTRIBUTE_LIFETIME_BOUND;
  512. T& operator*() & ABSL_ATTRIBUTE_LIFETIME_BOUND;
  513. const T&& operator*() const&& ABSL_ATTRIBUTE_LIFETIME_BOUND;
  514. T&& operator*() && ABSL_ATTRIBUTE_LIFETIME_BOUND;
  515. // StatusOr<T>::operator->()
  516. //
  517. // Returns a pointer to the current value.
  518. //
  519. // REQUIRES: `this->ok() == true`, otherwise the behavior is undefined.
  520. //
  521. // Use `this->ok()` to verify that there is a current value.
  522. const T* operator->() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
  523. T* operator->() ABSL_ATTRIBUTE_LIFETIME_BOUND;
  524. // StatusOr<T>::value_or()
  525. //
  526. // Returns the current value if `this->ok() == true`. Otherwise constructs a
  527. // value using the provided `default_value`.
  528. //
  529. // Unlike `value`, this function returns by value, copying the current value
  530. // if necessary. If the value type supports an efficient move, it can be used
  531. // as follows:
  532. //
  533. // T value = std::move(statusor).value_or(def);
  534. //
  535. // Unlike with `value`, calling `std::move()` on the result of `value_or` will
  536. // still trigger a copy.
  537. template <typename U>
  538. T value_or(U&& default_value) const&;
  539. template <typename U>
  540. T value_or(U&& default_value) &&;
  541. // StatusOr<T>::IgnoreError()
  542. //
  543. // Ignores any errors. This method does nothing except potentially suppress
  544. // complaints from any tools that are checking that errors are not dropped on
  545. // the floor.
  546. void IgnoreError() const;
  547. // StatusOr<T>::emplace()
  548. //
  549. // Reconstructs the inner value T in-place using the provided args, using the
  550. // T(args...) constructor. Returns reference to the reconstructed `T`.
  551. template <typename... Args>
  552. T& emplace(Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  553. if (ok()) {
  554. this->Clear();
  555. this->MakeValue(std::forward<Args>(args)...);
  556. } else {
  557. this->MakeValue(std::forward<Args>(args)...);
  558. this->status_ = absl::OkStatus();
  559. }
  560. return this->data_;
  561. }
  562. template <
  563. typename U, typename... Args,
  564. absl::enable_if_t<
  565. std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value,
  566. int> = 0>
  567. T& emplace(std::initializer_list<U> ilist,
  568. Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND {
  569. if (ok()) {
  570. this->Clear();
  571. this->MakeValue(ilist, std::forward<Args>(args)...);
  572. } else {
  573. this->MakeValue(ilist, std::forward<Args>(args)...);
  574. this->status_ = absl::OkStatus();
  575. }
  576. return this->data_;
  577. }
  578. // StatusOr<T>::AssignStatus()
  579. //
  580. // Sets the status of `absl::StatusOr<T>` to the given non-ok status value.
  581. //
  582. // NOTE: We recommend using the constructor and `operator=` where possible.
  583. // This method is intended for use in generic programming, to enable setting
  584. // the status of a `StatusOr<T>` when `T` may be `Status`. In that case, the
  585. // constructor and `operator=` would assign into the inner value of type
  586. // `Status`, rather than status of the `StatusOr` (b/280392796).
  587. //
  588. // REQUIRES: !Status(std::forward<U>(v)).ok(). This requirement is DCHECKed.
  589. // In optimized builds, passing absl::OkStatus() here will have the effect
  590. // of passing absl::StatusCode::kInternal as a fallback.
  591. using internal_statusor::StatusOrData<T>::AssignStatus;
  592. private:
  593. using internal_statusor::StatusOrData<T>::Assign;
  594. template <typename U>
  595. void Assign(const absl::StatusOr<U>& other);
  596. template <typename U>
  597. void Assign(absl::StatusOr<U>&& other);
  598. };
  599. // operator==()
  600. //
  601. // This operator checks the equality of two `absl::StatusOr<T>` objects.
  602. template <typename T>
  603. bool operator==(const StatusOr<T>& lhs, const StatusOr<T>& rhs) {
  604. if (lhs.ok() && rhs.ok()) return *lhs == *rhs;
  605. return lhs.status() == rhs.status();
  606. }
  607. // operator!=()
  608. //
  609. // This operator checks the inequality of two `absl::StatusOr<T>` objects.
  610. template <typename T>
  611. bool operator!=(const StatusOr<T>& lhs, const StatusOr<T>& rhs) {
  612. return !(lhs == rhs);
  613. }
  614. // Prints the `value` or the status in brackets to `os`.
  615. //
  616. // Requires `T` supports `operator<<`. Do not rely on the output format which
  617. // may change without notice.
  618. template <typename T, typename std::enable_if<
  619. absl::HasOstreamOperator<T>::value, int>::type = 0>
  620. std::ostream& operator<<(std::ostream& os, const StatusOr<T>& status_or) {
  621. if (status_or.ok()) {
  622. os << status_or.value();
  623. } else {
  624. os << internal_statusor::StringifyRandom::OpenBrackets()
  625. << status_or.status()
  626. << internal_statusor::StringifyRandom::CloseBrackets();
  627. }
  628. return os;
  629. }
  630. // As above, but supports `StrCat`, `StrFormat`, etc.
  631. //
  632. // Requires `T` has `AbslStringify`. Do not rely on the output format which
  633. // may change without notice.
  634. template <
  635. typename Sink, typename T,
  636. typename std::enable_if<absl::HasAbslStringify<T>::value, int>::type = 0>
  637. void AbslStringify(Sink& sink, const StatusOr<T>& status_or) {
  638. if (status_or.ok()) {
  639. absl::Format(&sink, "%v", status_or.value());
  640. } else {
  641. absl::Format(&sink, "%s%v%s",
  642. internal_statusor::StringifyRandom::OpenBrackets(),
  643. status_or.status(),
  644. internal_statusor::StringifyRandom::CloseBrackets());
  645. }
  646. }
  647. //------------------------------------------------------------------------------
  648. // Implementation details for StatusOr<T>
  649. //------------------------------------------------------------------------------
  650. // TODO(sbenza): avoid the string here completely.
  651. template <typename T>
  652. StatusOr<T>::StatusOr() : Base(Status(absl::StatusCode::kUnknown, "")) {}
  653. template <typename T>
  654. template <typename U>
  655. inline void StatusOr<T>::Assign(const StatusOr<U>& other) {
  656. if (other.ok()) {
  657. this->Assign(*other);
  658. } else {
  659. this->AssignStatus(other.status());
  660. }
  661. }
  662. template <typename T>
  663. template <typename U>
  664. inline void StatusOr<T>::Assign(StatusOr<U>&& other) {
  665. if (other.ok()) {
  666. this->Assign(*std::move(other));
  667. } else {
  668. this->AssignStatus(std::move(other).status());
  669. }
  670. }
  671. template <typename T>
  672. template <typename... Args>
  673. StatusOr<T>::StatusOr(absl::in_place_t, Args&&... args)
  674. : Base(absl::in_place, std::forward<Args>(args)...) {}
  675. template <typename T>
  676. template <typename U, typename... Args>
  677. StatusOr<T>::StatusOr(absl::in_place_t, std::initializer_list<U> ilist,
  678. Args&&... args)
  679. : Base(absl::in_place, ilist, std::forward<Args>(args)...) {}
  680. template <typename T>
  681. const Status& StatusOr<T>::status() const& {
  682. return this->status_;
  683. }
  684. template <typename T>
  685. Status StatusOr<T>::status() && {
  686. return ok() ? OkStatus() : std::move(this->status_);
  687. }
  688. template <typename T>
  689. const T& StatusOr<T>::value() const& {
  690. if (!this->ok()) internal_statusor::ThrowBadStatusOrAccess(this->status_);
  691. return this->data_;
  692. }
  693. template <typename T>
  694. T& StatusOr<T>::value() & {
  695. if (!this->ok()) internal_statusor::ThrowBadStatusOrAccess(this->status_);
  696. return this->data_;
  697. }
  698. template <typename T>
  699. const T&& StatusOr<T>::value() const&& {
  700. if (!this->ok()) {
  701. internal_statusor::ThrowBadStatusOrAccess(std::move(this->status_));
  702. }
  703. return std::move(this->data_);
  704. }
  705. template <typename T>
  706. T&& StatusOr<T>::value() && {
  707. if (!this->ok()) {
  708. internal_statusor::ThrowBadStatusOrAccess(std::move(this->status_));
  709. }
  710. return std::move(this->data_);
  711. }
  712. template <typename T>
  713. const T& StatusOr<T>::operator*() const& {
  714. this->EnsureOk();
  715. return this->data_;
  716. }
  717. template <typename T>
  718. T& StatusOr<T>::operator*() & {
  719. this->EnsureOk();
  720. return this->data_;
  721. }
  722. template <typename T>
  723. const T&& StatusOr<T>::operator*() const&& {
  724. this->EnsureOk();
  725. return std::move(this->data_);
  726. }
  727. template <typename T>
  728. T&& StatusOr<T>::operator*() && {
  729. this->EnsureOk();
  730. return std::move(this->data_);
  731. }
  732. template <typename T>
  733. absl::Nonnull<const T*> StatusOr<T>::operator->() const {
  734. this->EnsureOk();
  735. return &this->data_;
  736. }
  737. template <typename T>
  738. absl::Nonnull<T*> StatusOr<T>::operator->() {
  739. this->EnsureOk();
  740. return &this->data_;
  741. }
  742. template <typename T>
  743. template <typename U>
  744. T StatusOr<T>::value_or(U&& default_value) const& {
  745. if (ok()) {
  746. return this->data_;
  747. }
  748. return std::forward<U>(default_value);
  749. }
  750. template <typename T>
  751. template <typename U>
  752. T StatusOr<T>::value_or(U&& default_value) && {
  753. if (ok()) {
  754. return std::move(this->data_);
  755. }
  756. return std::forward<U>(default_value);
  757. }
  758. template <typename T>
  759. void StatusOr<T>::IgnoreError() const {
  760. // no-op
  761. }
  762. ABSL_NAMESPACE_END
  763. } // namespace absl
  764. #endif // ABSL_STATUS_STATUSOR_H_