You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

statusor.h 32 kB

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