result.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /* A partial result based on std::variant and proposed std::error
  2. (C) 2020-2021 Niall Douglas <http://www.nedproductions.biz/> (11 commits)
  3. File Created: Jan 2020
  4. Boost Software License - Version 1.0 - August 17th, 2003
  5. Permission is hereby granted, free of charge, to any person or organization
  6. obtaining a copy of the software and accompanying documentation covered by
  7. this license (the "Software") to use, reproduce, display, distribute,
  8. execute, and transmit the Software, and to prepare derivative works of the
  9. Software, and to permit third-parties to whom the Software is furnished to
  10. do so, all subject to the following:
  11. The copyright notices in the Software and this entire statement, including
  12. the above license grant, this restriction and the following disclaimer,
  13. must be included in all copies of the Software, in whole or in part, and
  14. all derivative works of the Software, unless such copies or derivative
  15. works are solely in the form of machine-executable object code generated by
  16. a source language processor.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  20. SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  21. FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  22. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. DEALINGS IN THE SOFTWARE.
  24. */
  25. #ifndef BOOST_OUTCOME_SYSTEM_ERROR2_RESULT_HPP
  26. #define BOOST_OUTCOME_SYSTEM_ERROR2_RESULT_HPP
  27. #include "error.hpp"
  28. #if __cplusplus >= 201703L || _HAS_CXX17
  29. #if __has_include(<variant>)
  30. #include <exception>
  31. #include <variant>
  32. BOOST_OUTCOME_SYSTEM_ERROR2_NAMESPACE_BEGIN
  33. template <class T> inline constexpr std::in_place_type_t<T> in_place_type{};
  34. template <class T> class result;
  35. //! \brief A trait for detecting result types
  36. template <class T> struct is_result : public std::false_type
  37. {
  38. };
  39. template <class T> struct is_result<result<T>> : public std::true_type
  40. {
  41. };
  42. /*! \brief Exception type representing the failure to retrieve an error.
  43. */
  44. class bad_result_access : public std::exception
  45. {
  46. public:
  47. bad_result_access() = default;
  48. //! Return an explanatory string
  49. virtual const char *what() const noexcept override { return "bad result access"; } // NOLINT
  50. };
  51. namespace detail
  52. {
  53. struct void_
  54. {
  55. };
  56. template <class T> using devoid = std::conditional_t<std::is_void_v<T>, void_, T>;
  57. } // namespace detail
  58. /*! \class result
  59. \brief A imperfect `result<T>` type with its error type hardcoded to `error`, only available on C++ 17 or later.
  60. Note that the proper `result<T>` type does not have the possibility of
  61. valueless by exception state. This implementation is therefore imperfect.
  62. */
  63. template <class T> class result : protected std::variant<BOOST_OUTCOME_SYSTEM_ERROR2_NAMESPACE::error, detail::devoid<T>>
  64. {
  65. using _base = std::variant<BOOST_OUTCOME_SYSTEM_ERROR2_NAMESPACE::error, detail::devoid<T>>;
  66. static_assert(!std::is_reference_v<T>, "Type cannot be a reference");
  67. static_assert(!std::is_array_v<T>, "Type cannot be an array");
  68. static_assert(!std::is_same_v<T, BOOST_OUTCOME_SYSTEM_ERROR2_NAMESPACE::error>, "Type cannot be a std::error");
  69. // not success nor failure types
  70. struct _implicit_converting_constructor_tag
  71. {
  72. };
  73. struct _explicit_converting_constructor_tag
  74. {
  75. };
  76. struct _implicit_constructor_tag
  77. {
  78. };
  79. struct _implicit_in_place_value_constructor_tag
  80. {
  81. };
  82. struct _implicit_in_place_error_constructor_tag
  83. {
  84. };
  85. public:
  86. //! The value type
  87. using value_type = T;
  88. //! The error type
  89. using error_type = BOOST_OUTCOME_SYSTEM_ERROR2_NAMESPACE::error;
  90. //! The value type, if it is available, else a usefully named unusable internal type
  91. using value_type_if_enabled = detail::devoid<T>;
  92. //! Used to rebind result types
  93. template <class U> using rebind = result<U>;
  94. protected:
  95. constexpr void _check() const
  96. {
  97. if(_base::index() == 0)
  98. {
  99. std::get_if<0>(this)->throw_exception();
  100. }
  101. }
  102. constexpr
  103. #ifdef _MSC_VER
  104. __declspec(noreturn)
  105. #elif defined(__GNUC__) || defined(__clang__)
  106. __attribute__((noreturn))
  107. #endif
  108. void _ub()
  109. {
  110. assert(false); // NOLINT
  111. #if defined(__GNUC__) || defined(__clang__)
  112. __builtin_unreachable();
  113. #elif defined(_MSC_VER)
  114. __assume(0);
  115. #endif
  116. }
  117. public:
  118. constexpr _base &_internal() noexcept { return *this; }
  119. constexpr const _base &_internal() const noexcept { return *this; }
  120. //! Default constructor is disabled
  121. result() = delete;
  122. //! Copy constructor
  123. result(const result &) = delete;
  124. //! Move constructor
  125. result(result &&) = default;
  126. //! Copy assignment
  127. result &operator=(const result &) = delete;
  128. //! Move assignment
  129. result &operator=(result &&) = default;
  130. //! Destructor
  131. ~result() = default;
  132. //! Implicit result converting move constructor
  133. template <class U, std::enable_if_t<std::is_convertible_v<U, T>, bool> = true>
  134. constexpr result(result<U> &&o, _implicit_converting_constructor_tag = {}) noexcept(std::is_nothrow_constructible_v<T, U>)
  135. : _base(std::move(o))
  136. {
  137. }
  138. //! Implicit result converting copy constructor
  139. template <class U, std::enable_if_t<std::is_convertible_v<U, T>, bool> = true>
  140. constexpr result(const result<U> &o, _implicit_converting_constructor_tag = {}) noexcept(std::is_nothrow_constructible_v<T, U>)
  141. : _base(o)
  142. {
  143. }
  144. //! Explicit result converting move constructor
  145. template <class U, std::enable_if_t<std::is_constructible_v<T, U>, bool> = true>
  146. constexpr explicit result(result<U> &&o, _explicit_converting_constructor_tag = {}) noexcept(std::is_nothrow_constructible_v<T, U>)
  147. : _base(std::move(o))
  148. {
  149. }
  150. //! Explicit result converting copy constructor
  151. template <class U, std::enable_if_t<std::is_constructible_v<T, U>, bool> = true>
  152. constexpr explicit result(const result<U> &o, _explicit_converting_constructor_tag = {}) noexcept(std::is_nothrow_constructible_v<T, U>)
  153. : _base(o)
  154. {
  155. }
  156. //! Anything which `std::variant<error, T>` will construct from, we shall implicitly construct from
  157. using _base::_base;
  158. //! Special case `in_place_type_t<void>`
  159. constexpr explicit result(std::in_place_type_t<void> /*unused*/) noexcept
  160. : _base(in_place_type<detail::void_>)
  161. {
  162. }
  163. //! Implicit in-place converting error constructor
  164. template <class Arg1, class Arg2, class... Args, //
  165. std::enable_if_t<!(std::is_constructible_v<value_type, Arg1, Arg2, Args...> && std::is_constructible_v<error_type, Arg1, Arg2, Args...>) //
  166. &&std::is_constructible_v<error_type, Arg1, Arg2, Args...>,
  167. bool> = true,
  168. long = 5>
  169. constexpr result(Arg1 &&arg1, Arg2 &&arg2, Args &&... args) noexcept(std::is_nothrow_constructible_v<error_type, Arg1, Arg2, Args...>)
  170. : _base(std::in_place_index<0>, std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Args>(args)...)
  171. {
  172. }
  173. //! Implicit in-place converting value constructor
  174. template <class Arg1, class Arg2, class... Args, //
  175. std::enable_if_t<!(std::is_constructible_v<value_type, Arg1, Arg2, Args...> && std::is_constructible_v<error_type, Arg1, Arg2, Args...>) //
  176. &&std::is_constructible_v<value_type, Arg1, Arg2, Args...>,
  177. bool> = true,
  178. int = 5>
  179. constexpr result(Arg1 &&arg1, Arg2 &&arg2, Args &&... args) noexcept(std::is_nothrow_constructible_v<value_type, Arg1, Arg2, Args...>)
  180. : _base(std::in_place_index<1>, std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Args>(args)...)
  181. {
  182. }
  183. //! Implicit construction from any type where an ADL discovered `make_status_code(T, Args ...)` returns a `status_code`.
  184. template <class U, class... Args, //
  185. class MakeStatusCodeResult = typename detail::safe_get_make_status_code_result<U, Args...>::type, // Safe ADL lookup of make_status_code(), returns void if not found
  186. typename std::enable_if<!std::is_same<typename std::decay<U>::type, result>::value // not copy/move of self
  187. && !std::is_same<typename std::decay<U>::type, value_type>::value // not copy/move of value type
  188. && is_status_code<MakeStatusCodeResult>::value // ADL makes a status code
  189. && std::is_constructible<error_type, MakeStatusCodeResult>::value, // ADLed status code is compatible
  190. bool>::type = true>
  191. constexpr result(U &&v, Args &&... args) noexcept(noexcept(make_status_code(std::declval<U>(), std::declval<Args>()...))) // NOLINT
  192. : _base(std::in_place_index<0>, make_status_code(static_cast<U &&>(v), static_cast<Args &&>(args)...))
  193. {
  194. }
  195. //! Swap with another result
  196. constexpr void swap(result &o) noexcept(std::is_nothrow_swappable_v<_base>) { _base::swap(o); }
  197. //! Clone the result
  198. constexpr result clone() const { return has_value() ? result(value()) : result(error().clone()); }
  199. //! True if result has a value
  200. constexpr bool has_value() const noexcept { return _base::index() == 1; }
  201. //! True if result has a value
  202. explicit operator bool() const noexcept { return has_value(); }
  203. //! True if result has an error
  204. constexpr bool has_error() const noexcept { return _base::index() == 0; }
  205. //! Accesses the value if one exists, else calls `.error().throw_exception()`.
  206. constexpr value_type_if_enabled &value() &
  207. {
  208. _check();
  209. return std::get<1>(*this);
  210. }
  211. //! Accesses the value if one exists, else calls `.error().throw_exception()`.
  212. constexpr const value_type_if_enabled &value() const &
  213. {
  214. _check();
  215. return std::get<1>(*this);
  216. }
  217. //! Accesses the value if one exists, else calls `.error().throw_exception()`.
  218. constexpr value_type_if_enabled &&value() &&
  219. {
  220. _check();
  221. return std::get<1>(std::move(*this));
  222. }
  223. //! Accesses the value if one exists, else calls `.error().throw_exception()`.
  224. constexpr const value_type_if_enabled &&value() const &&
  225. {
  226. _check();
  227. return std::get<1>(std::move(*this));
  228. }
  229. //! Accesses the error if one exists, else throws `bad_result_access`.
  230. constexpr error_type &error() &
  231. {
  232. if(!has_error())
  233. {
  234. #ifndef BOOST_NO_EXCEPTIONS
  235. throw bad_result_access();
  236. #else
  237. abort();
  238. #endif
  239. }
  240. return *std::get_if<0>(this);
  241. }
  242. //! Accesses the error if one exists, else throws `bad_result_access`.
  243. constexpr const error_type &error() const &
  244. {
  245. if(!has_error())
  246. {
  247. #ifndef BOOST_NO_EXCEPTIONS
  248. throw bad_result_access();
  249. #else
  250. abort();
  251. #endif
  252. }
  253. return *std::get_if<0>(this);
  254. }
  255. //! Accesses the error if one exists, else throws `bad_result_access`.
  256. constexpr error_type &&error() &&
  257. {
  258. if(!has_error())
  259. {
  260. #ifndef BOOST_NO_EXCEPTIONS
  261. throw bad_result_access();
  262. #else
  263. abort();
  264. #endif
  265. }
  266. return std::move(*std::get_if<0>(this));
  267. }
  268. //! Accesses the error if one exists, else throws `bad_result_access`.
  269. constexpr const error_type &&error() const &&
  270. {
  271. if(!has_error())
  272. {
  273. #ifndef BOOST_NO_EXCEPTIONS
  274. throw bad_result_access();
  275. #else
  276. abort();
  277. #endif
  278. }
  279. return std::move(*std::get_if<0>(this));
  280. }
  281. //! Accesses the value, being UB if none exists
  282. constexpr value_type_if_enabled &assume_value() & noexcept
  283. {
  284. if(!has_value())
  285. {
  286. _ub();
  287. }
  288. return *std::get_if<1>(this);
  289. }
  290. //! Accesses the error, being UB if none exists
  291. constexpr const value_type_if_enabled &assume_value() const &noexcept
  292. {
  293. if(!has_value())
  294. {
  295. _ub();
  296. }
  297. return *std::get_if<1>(this);
  298. }
  299. //! Accesses the error, being UB if none exists
  300. constexpr value_type_if_enabled &&assume_value() && noexcept
  301. {
  302. if(!has_value())
  303. {
  304. _ub();
  305. }
  306. return std::move(*std::get_if<1>(this));
  307. }
  308. //! Accesses the error, being UB if none exists
  309. constexpr const value_type_if_enabled &&assume_value() const &&noexcept
  310. {
  311. if(!has_value())
  312. {
  313. _ub();
  314. }
  315. return std::move(*std::get_if<1>(this));
  316. }
  317. //! Accesses the error, being UB if none exists
  318. constexpr error_type &assume_error() & noexcept
  319. {
  320. if(!has_error())
  321. {
  322. _ub();
  323. }
  324. return *std::get_if<0>(this);
  325. }
  326. //! Accesses the error, being UB if none exists
  327. constexpr const error_type &assume_error() const &noexcept
  328. {
  329. if(!has_error())
  330. {
  331. _ub();
  332. }
  333. return *std::get_if<0>(this);
  334. }
  335. //! Accesses the error, being UB if none exists
  336. constexpr error_type &&assume_error() && noexcept
  337. {
  338. if(!has_error())
  339. {
  340. _ub();
  341. }
  342. return std::move(*std::get_if<0>(this));
  343. }
  344. //! Accesses the error, being UB if none exists
  345. constexpr const error_type &&assume_error() const &&noexcept
  346. {
  347. if(!has_error())
  348. {
  349. _ub();
  350. }
  351. return std::move(*std::get_if<0>(this));
  352. }
  353. };
  354. //! True if the two results compare equal.
  355. template <class T, class U, typename = decltype(std::declval<T>() == std::declval<U>())> constexpr inline bool operator==(const result<T> &a, const result<U> &b) noexcept
  356. {
  357. const auto &x = a._internal();
  358. return x == b;
  359. }
  360. //! True if the two results compare unequal.
  361. template <class T, class U, typename = decltype(std::declval<T>() != std::declval<U>())> constexpr inline bool operator!=(const result<T> &a, const result<U> &b) noexcept
  362. {
  363. const auto &x = a._internal();
  364. return x != b;
  365. }
  366. BOOST_OUTCOME_SYSTEM_ERROR2_NAMESPACE_END
  367. #endif
  368. #endif
  369. #endif