statusor.h 28 KB

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