statusor_internal.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. #ifndef ABSL_STATUS_INTERNAL_STATUSOR_INTERNAL_H_
  15. #define ABSL_STATUS_INTERNAL_STATUSOR_INTERNAL_H_
  16. #include <cstdint>
  17. #include <type_traits>
  18. #include <utility>
  19. #include "absl/base/attributes.h"
  20. #include "absl/base/nullability.h"
  21. #include "absl/meta/type_traits.h"
  22. #include "absl/status/status.h"
  23. #include "absl/strings/string_view.h"
  24. #include "absl/utility/utility.h"
  25. namespace absl {
  26. ABSL_NAMESPACE_BEGIN
  27. template <typename T>
  28. class ABSL_MUST_USE_RESULT StatusOr;
  29. namespace internal_statusor {
  30. // Detects whether `U` has conversion operator to `StatusOr<T>`, i.e. `operator
  31. // StatusOr<T>()`.
  32. template <typename T, typename U, typename = void>
  33. struct HasConversionOperatorToStatusOr : std::false_type {};
  34. template <typename T, typename U>
  35. void test(char (*)[sizeof(std::declval<U>().operator absl::StatusOr<T>())]);
  36. template <typename T, typename U>
  37. struct HasConversionOperatorToStatusOr<T, U, decltype(test<T, U>(0))>
  38. : std::true_type {};
  39. // Detects whether `T` is constructible or convertible from `StatusOr<U>`.
  40. template <typename T, typename U>
  41. using IsConstructibleOrConvertibleFromStatusOr =
  42. absl::disjunction<std::is_constructible<T, StatusOr<U>&>,
  43. std::is_constructible<T, const StatusOr<U>&>,
  44. std::is_constructible<T, StatusOr<U>&&>,
  45. std::is_constructible<T, const StatusOr<U>&&>,
  46. std::is_convertible<StatusOr<U>&, T>,
  47. std::is_convertible<const StatusOr<U>&, T>,
  48. std::is_convertible<StatusOr<U>&&, T>,
  49. std::is_convertible<const StatusOr<U>&&, T>>;
  50. // Detects whether `T` is constructible or convertible or assignable from
  51. // `StatusOr<U>`.
  52. template <typename T, typename U>
  53. using IsConstructibleOrConvertibleOrAssignableFromStatusOr =
  54. absl::disjunction<IsConstructibleOrConvertibleFromStatusOr<T, U>,
  55. std::is_assignable<T&, StatusOr<U>&>,
  56. std::is_assignable<T&, const StatusOr<U>&>,
  57. std::is_assignable<T&, StatusOr<U>&&>,
  58. std::is_assignable<T&, const StatusOr<U>&&>>;
  59. // Detects whether direct initializing `StatusOr<T>` from `U` is ambiguous, i.e.
  60. // when `U` is `StatusOr<V>` and `T` is constructible or convertible from `V`.
  61. template <typename T, typename U>
  62. struct IsDirectInitializationAmbiguous
  63. : public absl::conditional_t<
  64. std::is_same<absl::remove_cvref_t<U>, U>::value, std::false_type,
  65. IsDirectInitializationAmbiguous<T, absl::remove_cvref_t<U>>> {};
  66. template <typename T, typename V>
  67. struct IsDirectInitializationAmbiguous<T, absl::StatusOr<V>>
  68. : public IsConstructibleOrConvertibleFromStatusOr<T, V> {};
  69. // Checks against the constraints of the direction initialization, i.e. when
  70. // `StatusOr<T>::StatusOr(U&&)` should participate in overload resolution.
  71. template <typename T, typename U>
  72. using IsDirectInitializationValid = absl::disjunction<
  73. // Short circuits if T is basically U.
  74. std::is_same<T, absl::remove_cvref_t<U>>,
  75. absl::negation<absl::disjunction<
  76. std::is_same<absl::StatusOr<T>, absl::remove_cvref_t<U>>,
  77. std::is_same<absl::Status, absl::remove_cvref_t<U>>,
  78. std::is_same<absl::in_place_t, absl::remove_cvref_t<U>>,
  79. IsDirectInitializationAmbiguous<T, U>>>>;
  80. // This trait detects whether `StatusOr<T>::operator=(U&&)` is ambiguous, which
  81. // is equivalent to whether all the following conditions are met:
  82. // 1. `U` is `StatusOr<V>`.
  83. // 2. `T` is constructible and assignable from `V`.
  84. // 3. `T` is constructible and assignable from `U` (i.e. `StatusOr<V>`).
  85. // For example, the following code is considered ambiguous:
  86. // (`T` is `bool`, `U` is `StatusOr<bool>`, `V` is `bool`)
  87. // StatusOr<bool> s1 = true; // s1.ok() && s1.ValueOrDie() == true
  88. // StatusOr<bool> s2 = false; // s2.ok() && s2.ValueOrDie() == false
  89. // s1 = s2; // ambiguous, `s1 = s2.ValueOrDie()` or `s1 = bool(s2)`?
  90. template <typename T, typename U>
  91. struct IsForwardingAssignmentAmbiguous
  92. : public absl::conditional_t<
  93. std::is_same<absl::remove_cvref_t<U>, U>::value, std::false_type,
  94. IsForwardingAssignmentAmbiguous<T, absl::remove_cvref_t<U>>> {};
  95. template <typename T, typename U>
  96. struct IsForwardingAssignmentAmbiguous<T, absl::StatusOr<U>>
  97. : public IsConstructibleOrConvertibleOrAssignableFromStatusOr<T, U> {};
  98. // Checks against the constraints of the forwarding assignment, i.e. whether
  99. // `StatusOr<T>::operator(U&&)` should participate in overload resolution.
  100. template <typename T, typename U>
  101. using IsForwardingAssignmentValid = absl::disjunction<
  102. // Short circuits if T is basically U.
  103. std::is_same<T, absl::remove_cvref_t<U>>,
  104. absl::negation<absl::disjunction<
  105. std::is_same<absl::StatusOr<T>, absl::remove_cvref_t<U>>,
  106. std::is_same<absl::Status, absl::remove_cvref_t<U>>,
  107. std::is_same<absl::in_place_t, absl::remove_cvref_t<U>>,
  108. IsForwardingAssignmentAmbiguous<T, U>>>>;
  109. class Helper {
  110. public:
  111. // Move type-agnostic error handling to the .cc.
  112. static void HandleInvalidStatusCtorArg(absl::Nonnull<Status*>);
  113. ABSL_ATTRIBUTE_NORETURN static void Crash(const absl::Status& status);
  114. };
  115. // Construct an instance of T in `p` through placement new, passing Args... to
  116. // the constructor.
  117. // This abstraction is here mostly for the gcc performance fix.
  118. template <typename T, typename... Args>
  119. ABSL_ATTRIBUTE_NONNULL(1)
  120. void PlacementNew(absl::Nonnull<void*> p, Args&&... args) {
  121. new (p) T(std::forward<Args>(args)...);
  122. }
  123. // Helper base class to hold the data and all operations.
  124. // We move all this to a base class to allow mixing with the appropriate
  125. // TraitsBase specialization.
  126. template <typename T>
  127. class StatusOrData {
  128. template <typename U>
  129. friend class StatusOrData;
  130. public:
  131. StatusOrData() = delete;
  132. StatusOrData(const StatusOrData& other) {
  133. if (other.ok()) {
  134. MakeValue(other.data_);
  135. MakeStatus();
  136. } else {
  137. MakeStatus(other.status_);
  138. }
  139. }
  140. StatusOrData(StatusOrData&& other) noexcept {
  141. if (other.ok()) {
  142. MakeValue(std::move(other.data_));
  143. MakeStatus();
  144. } else {
  145. MakeStatus(std::move(other.status_));
  146. }
  147. }
  148. template <typename U>
  149. explicit StatusOrData(const StatusOrData<U>& other) {
  150. if (other.ok()) {
  151. MakeValue(other.data_);
  152. MakeStatus();
  153. } else {
  154. MakeStatus(other.status_);
  155. }
  156. }
  157. template <typename U>
  158. explicit StatusOrData(StatusOrData<U>&& other) {
  159. if (other.ok()) {
  160. MakeValue(std::move(other.data_));
  161. MakeStatus();
  162. } else {
  163. MakeStatus(std::move(other.status_));
  164. }
  165. }
  166. template <typename... Args>
  167. explicit StatusOrData(absl::in_place_t, Args&&... args)
  168. : data_(std::forward<Args>(args)...) {
  169. MakeStatus();
  170. }
  171. explicit StatusOrData(const T& value) : data_(value) {
  172. MakeStatus();
  173. }
  174. explicit StatusOrData(T&& value) : data_(std::move(value)) {
  175. MakeStatus();
  176. }
  177. template <typename U,
  178. absl::enable_if_t<std::is_constructible<absl::Status, U&&>::value,
  179. int> = 0>
  180. explicit StatusOrData(U&& v) : status_(std::forward<U>(v)) {
  181. EnsureNotOk();
  182. }
  183. StatusOrData& operator=(const StatusOrData& other) {
  184. if (this == &other) return *this;
  185. if (other.ok())
  186. Assign(other.data_);
  187. else
  188. AssignStatus(other.status_);
  189. return *this;
  190. }
  191. StatusOrData& operator=(StatusOrData&& other) {
  192. if (this == &other) return *this;
  193. if (other.ok())
  194. Assign(std::move(other.data_));
  195. else
  196. AssignStatus(std::move(other.status_));
  197. return *this;
  198. }
  199. ~StatusOrData() {
  200. if (ok()) {
  201. status_.~Status();
  202. data_.~T();
  203. } else {
  204. status_.~Status();
  205. }
  206. }
  207. template <typename U>
  208. void Assign(U&& value) {
  209. if (ok()) {
  210. data_ = std::forward<U>(value);
  211. } else {
  212. MakeValue(std::forward<U>(value));
  213. status_ = OkStatus();
  214. }
  215. }
  216. template <typename U>
  217. void AssignStatus(U&& v) {
  218. Clear();
  219. status_ = static_cast<absl::Status>(std::forward<U>(v));
  220. EnsureNotOk();
  221. }
  222. bool ok() const { return status_.ok(); }
  223. protected:
  224. // status_ will always be active after the constructor.
  225. // We make it a union to be able to initialize exactly how we need without
  226. // waste.
  227. // Eg. in the copy constructor we use the default constructor of Status in
  228. // the ok() path to avoid an extra Ref call.
  229. union {
  230. Status status_;
  231. };
  232. // data_ is active iff status_.ok()==true
  233. struct Dummy {};
  234. union {
  235. // When T is const, we need some non-const object we can cast to void* for
  236. // the placement new. dummy_ is that object.
  237. Dummy dummy_;
  238. T data_;
  239. };
  240. void Clear() {
  241. if (ok()) data_.~T();
  242. }
  243. void EnsureOk() const {
  244. if (ABSL_PREDICT_FALSE(!ok())) Helper::Crash(status_);
  245. }
  246. void EnsureNotOk() {
  247. if (ABSL_PREDICT_FALSE(ok())) Helper::HandleInvalidStatusCtorArg(&status_);
  248. }
  249. // Construct the value (ie. data_) through placement new with the passed
  250. // argument.
  251. template <typename... Arg>
  252. void MakeValue(Arg&&... arg) {
  253. internal_statusor::PlacementNew<T>(&dummy_, std::forward<Arg>(arg)...);
  254. }
  255. // Construct the status (ie. status_) through placement new with the passed
  256. // argument.
  257. template <typename... Args>
  258. void MakeStatus(Args&&... args) {
  259. internal_statusor::PlacementNew<Status>(&status_,
  260. std::forward<Args>(args)...);
  261. }
  262. };
  263. // Helper base classes to allow implicitly deleted constructors and assignment
  264. // operators in `StatusOr`. For example, `CopyCtorBase` will explicitly delete
  265. // the copy constructor when T is not copy constructible and `StatusOr` will
  266. // inherit that behavior implicitly.
  267. template <typename T, bool = std::is_copy_constructible<T>::value>
  268. struct CopyCtorBase {
  269. CopyCtorBase() = default;
  270. CopyCtorBase(const CopyCtorBase&) = default;
  271. CopyCtorBase(CopyCtorBase&&) = default;
  272. CopyCtorBase& operator=(const CopyCtorBase&) = default;
  273. CopyCtorBase& operator=(CopyCtorBase&&) = default;
  274. };
  275. template <typename T>
  276. struct CopyCtorBase<T, false> {
  277. CopyCtorBase() = default;
  278. CopyCtorBase(const CopyCtorBase&) = delete;
  279. CopyCtorBase(CopyCtorBase&&) = default;
  280. CopyCtorBase& operator=(const CopyCtorBase&) = default;
  281. CopyCtorBase& operator=(CopyCtorBase&&) = default;
  282. };
  283. template <typename T, bool = std::is_move_constructible<T>::value>
  284. struct MoveCtorBase {
  285. MoveCtorBase() = default;
  286. MoveCtorBase(const MoveCtorBase&) = default;
  287. MoveCtorBase(MoveCtorBase&&) = default;
  288. MoveCtorBase& operator=(const MoveCtorBase&) = default;
  289. MoveCtorBase& operator=(MoveCtorBase&&) = default;
  290. };
  291. template <typename T>
  292. struct MoveCtorBase<T, false> {
  293. MoveCtorBase() = default;
  294. MoveCtorBase(const MoveCtorBase&) = default;
  295. MoveCtorBase(MoveCtorBase&&) = delete;
  296. MoveCtorBase& operator=(const MoveCtorBase&) = default;
  297. MoveCtorBase& operator=(MoveCtorBase&&) = default;
  298. };
  299. template <typename T, bool = std::is_copy_constructible<T>::value&&
  300. std::is_copy_assignable<T>::value>
  301. struct CopyAssignBase {
  302. CopyAssignBase() = default;
  303. CopyAssignBase(const CopyAssignBase&) = default;
  304. CopyAssignBase(CopyAssignBase&&) = default;
  305. CopyAssignBase& operator=(const CopyAssignBase&) = default;
  306. CopyAssignBase& operator=(CopyAssignBase&&) = default;
  307. };
  308. template <typename T>
  309. struct CopyAssignBase<T, false> {
  310. CopyAssignBase() = default;
  311. CopyAssignBase(const CopyAssignBase&) = default;
  312. CopyAssignBase(CopyAssignBase&&) = default;
  313. CopyAssignBase& operator=(const CopyAssignBase&) = delete;
  314. CopyAssignBase& operator=(CopyAssignBase&&) = default;
  315. };
  316. template <typename T, bool = std::is_move_constructible<T>::value&&
  317. std::is_move_assignable<T>::value>
  318. struct MoveAssignBase {
  319. MoveAssignBase() = default;
  320. MoveAssignBase(const MoveAssignBase&) = default;
  321. MoveAssignBase(MoveAssignBase&&) = default;
  322. MoveAssignBase& operator=(const MoveAssignBase&) = default;
  323. MoveAssignBase& operator=(MoveAssignBase&&) = default;
  324. };
  325. template <typename T>
  326. struct MoveAssignBase<T, false> {
  327. MoveAssignBase() = default;
  328. MoveAssignBase(const MoveAssignBase&) = default;
  329. MoveAssignBase(MoveAssignBase&&) = default;
  330. MoveAssignBase& operator=(const MoveAssignBase&) = default;
  331. MoveAssignBase& operator=(MoveAssignBase&&) = delete;
  332. };
  333. ABSL_ATTRIBUTE_NORETURN void ThrowBadStatusOrAccess(absl::Status status);
  334. // Used to introduce jitter into the output of printing functions for
  335. // `StatusOr` (i.e. `AbslStringify` and `operator<<`).
  336. class StringifyRandom {
  337. enum BracesType {
  338. kBareParens = 0,
  339. kSpaceParens,
  340. kBareBrackets,
  341. kSpaceBrackets,
  342. };
  343. // Returns a random `BracesType` determined once per binary load.
  344. static BracesType RandomBraces() {
  345. static const BracesType kRandomBraces = static_cast<BracesType>(
  346. (reinterpret_cast<uintptr_t>(&kRandomBraces) >> 4) % 4);
  347. return kRandomBraces;
  348. }
  349. public:
  350. static inline absl::string_view OpenBrackets() {
  351. switch (RandomBraces()) {
  352. case kBareParens:
  353. return "(";
  354. case kSpaceParens:
  355. return "( ";
  356. case kBareBrackets:
  357. return "[";
  358. case kSpaceBrackets:
  359. return "[ ";
  360. }
  361. return "(";
  362. }
  363. static inline absl::string_view CloseBrackets() {
  364. switch (RandomBraces()) {
  365. case kBareParens:
  366. return ")";
  367. case kSpaceParens:
  368. return " )";
  369. case kBareBrackets:
  370. return "]";
  371. case kSpaceBrackets:
  372. return " ]";
  373. }
  374. return ")";
  375. }
  376. };
  377. } // namespace internal_statusor
  378. ABSL_NAMESPACE_END
  379. } // namespace absl
  380. #endif // ABSL_STATUS_INTERNAL_STATUSOR_INTERNAL_H_