status_code_domain.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /* Proposed SG14 status_code
  2. (C) 2018-2019 Niall Douglas <http://www.nedproductions.biz/> (5 commits)
  3. File Created: Feb 2018
  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_STATUS_CODE_DOMAIN_HPP
  26. #define BOOST_OUTCOME_SYSTEM_ERROR2_STATUS_CODE_DOMAIN_HPP
  27. #include "config.hpp"
  28. #include <cstring> // for strchr
  29. BOOST_OUTCOME_SYSTEM_ERROR2_NAMESPACE_BEGIN
  30. /*! The main workhorse of the system_error2 library, can be typed (`status_code<DomainType>`), erased-immutable (`status_code<void>`) or erased-mutable (`status_code<erased<T>>`).
  31. Be careful of placing these into containers! Equality and inequality operators are
  32. *semantic* not exact. Therefore two distinct items will test true! To help prevent
  33. surprise on this, `operator<` and `std::hash<>` are NOT implemented in order to
  34. trap potential incorrectness. Define your own custom comparison functions for your
  35. container which perform exact comparisons.
  36. */
  37. template <class DomainType> class status_code;
  38. class _generic_code_domain;
  39. //! The generic code is a status code with the generic code domain, which is that of `errc` (POSIX).
  40. using generic_code = status_code<_generic_code_domain>;
  41. namespace detail
  42. {
  43. template <class StatusCode> class indirecting_domain;
  44. template <class T> struct status_code_sizer
  45. {
  46. void *a;
  47. T b;
  48. };
  49. template <class To, class From> struct type_erasure_is_safe
  50. {
  51. static constexpr bool value = traits::is_move_relocating<From>::value //
  52. && (sizeof(status_code_sizer<From>) <= sizeof(status_code_sizer<To>));
  53. };
  54. } // namespace detail
  55. /*! Abstract base class for a coding domain of a status code.
  56. */
  57. class status_code_domain
  58. {
  59. template <class DomainType> friend class status_code;
  60. template <class StatusCode> friend class indirecting_domain;
  61. public:
  62. //! Type of the unique id for this domain.
  63. using unique_id_type = unsigned long long;
  64. /*! (Potentially thread safe) Reference to a message string.
  65. Be aware that you cannot add payload to implementations of this class.
  66. You get exactly the `void *[3]` array to keep state, this is usually
  67. sufficient for a `std::shared_ptr<>` or a `std::string`.
  68. You can install a handler to be called when this object is copied,
  69. moved and destructed. This takes the form of a C function pointer.
  70. */
  71. class string_ref
  72. {
  73. public:
  74. //! The value type
  75. using value_type = const char;
  76. //! The size type
  77. using size_type = size_t;
  78. //! The pointer type
  79. using pointer = const char *;
  80. //! The const pointer type
  81. using const_pointer = const char *;
  82. //! The iterator type
  83. using iterator = const char *;
  84. //! The const iterator type
  85. using const_iterator = const char *;
  86. protected:
  87. //! The operation occurring
  88. enum class _thunk_op
  89. {
  90. copy,
  91. move,
  92. destruct
  93. };
  94. //! The prototype of the handler function. Copies can throw, moves and destructs cannot.
  95. using _thunk_spec = void (*)(string_ref *dest, const string_ref *src, _thunk_op op);
  96. #ifndef NDEBUG
  97. private:
  98. static void _checking_string_thunk(string_ref *dest, const string_ref *src, _thunk_op /*unused*/) noexcept
  99. {
  100. (void) dest;
  101. (void) src;
  102. assert(dest->_thunk == _checking_string_thunk); // NOLINT
  103. assert(src == nullptr || src->_thunk == _checking_string_thunk); // NOLINT
  104. // do nothing
  105. }
  106. protected:
  107. #endif
  108. //! Pointers to beginning and end of character range
  109. pointer _begin{}, _end{};
  110. //! Three `void*` of state
  111. void *_state[3]{}; // at least the size of a shared_ptr
  112. //! Handler for when operations occur
  113. const _thunk_spec _thunk{nullptr};
  114. constexpr explicit string_ref(_thunk_spec thunk) noexcept : _thunk(thunk) {}
  115. public:
  116. //! Construct from a C string literal
  117. BOOST_OUTCOME_SYSTEM_ERROR2_CONSTEXPR14 explicit string_ref(const char *str, size_type len = static_cast<size_type>(-1), void *state0 = nullptr, void *state1 = nullptr, void *state2 = nullptr,
  118. #ifndef NDEBUG
  119. _thunk_spec thunk = _checking_string_thunk
  120. #else
  121. _thunk_spec thunk = nullptr
  122. #endif
  123. ) noexcept : _begin(str),
  124. _end((len == static_cast<size_type>(-1)) ? (str + detail::cstrlen(str)) : (str + len)), // NOLINT
  125. _state{state0, state1, state2},
  126. _thunk(thunk)
  127. {
  128. }
  129. //! Copy construct the derived implementation.
  130. string_ref(const string_ref &o)
  131. : _begin(o._begin)
  132. , _end(o._end)
  133. , _state{o._state[0], o._state[1], o._state[2]}
  134. , _thunk(o._thunk)
  135. {
  136. if(_thunk != nullptr)
  137. {
  138. _thunk(this, &o, _thunk_op::copy);
  139. }
  140. }
  141. //! Move construct the derived implementation.
  142. string_ref(string_ref &&o) noexcept : _begin(o._begin), _end(o._end), _state{o._state[0], o._state[1], o._state[2]}, _thunk(o._thunk)
  143. {
  144. if(_thunk != nullptr)
  145. {
  146. _thunk(this, &o, _thunk_op::move);
  147. }
  148. }
  149. //! Copy assignment
  150. string_ref &operator=(const string_ref &o)
  151. {
  152. if(this != &o)
  153. {
  154. #if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)
  155. string_ref temp(static_cast<string_ref &&>(*this));
  156. this->~string_ref();
  157. try
  158. {
  159. new(this) string_ref(o); // may throw
  160. }
  161. catch(...)
  162. {
  163. new(this) string_ref(static_cast<string_ref &&>(temp));
  164. throw;
  165. }
  166. #else
  167. this->~string_ref();
  168. new(this) string_ref(o);
  169. #endif
  170. }
  171. return *this;
  172. }
  173. //! Move assignment
  174. string_ref &operator=(string_ref &&o) noexcept
  175. {
  176. if(this != &o)
  177. {
  178. this->~string_ref();
  179. new(this) string_ref(static_cast<string_ref &&>(o));
  180. }
  181. return *this;
  182. }
  183. //! Destruction
  184. ~string_ref()
  185. {
  186. if(_thunk != nullptr)
  187. {
  188. _thunk(this, nullptr, _thunk_op::destruct);
  189. }
  190. _begin = _end = nullptr;
  191. }
  192. //! Returns whether the reference is empty or not
  193. BOOST_OUTCOME_SYSTEM_ERROR2_NODISCARD bool empty() const noexcept { return _begin == _end; }
  194. //! Returns the size of the string
  195. size_type size() const noexcept { return _end - _begin; }
  196. //! Returns a null terminated C string
  197. const_pointer c_str() const noexcept { return _begin; }
  198. //! Returns a null terminated C string
  199. const_pointer data() const noexcept { return _begin; }
  200. //! Returns the beginning of the string
  201. iterator begin() noexcept { return _begin; }
  202. //! Returns the beginning of the string
  203. const_iterator begin() const noexcept { return _begin; }
  204. //! Returns the beginning of the string
  205. const_iterator cbegin() const noexcept { return _begin; }
  206. //! Returns the end of the string
  207. iterator end() noexcept { return _end; }
  208. //! Returns the end of the string
  209. const_iterator end() const noexcept { return _end; }
  210. //! Returns the end of the string
  211. const_iterator cend() const noexcept { return _end; }
  212. };
  213. /*! A reference counted, threadsafe reference to a message string.
  214. */
  215. class atomic_refcounted_string_ref : public string_ref
  216. {
  217. struct _allocated_msg
  218. {
  219. mutable std::atomic<unsigned> count{1};
  220. };
  221. _allocated_msg *&_msg() noexcept { return reinterpret_cast<_allocated_msg *&>(this->_state[0]); } // NOLINT
  222. const _allocated_msg *_msg() const noexcept { return reinterpret_cast<const _allocated_msg *>(this->_state[0]); } // NOLINT
  223. static void _refcounted_string_thunk(string_ref *_dest, const string_ref *_src, _thunk_op op) noexcept
  224. {
  225. auto dest = static_cast<atomic_refcounted_string_ref *>(_dest); // NOLINT
  226. auto src = static_cast<const atomic_refcounted_string_ref *>(_src); // NOLINT
  227. (void) src;
  228. assert(dest->_thunk == _refcounted_string_thunk); // NOLINT
  229. assert(src == nullptr || src->_thunk == _refcounted_string_thunk); // NOLINT
  230. switch(op)
  231. {
  232. case _thunk_op::copy:
  233. {
  234. if(dest->_msg() != nullptr)
  235. {
  236. auto count = dest->_msg()->count.fetch_add(1, std::memory_order_relaxed);
  237. (void) count;
  238. assert(count != 0); // NOLINT
  239. }
  240. return;
  241. }
  242. case _thunk_op::move:
  243. {
  244. assert(src); // NOLINT
  245. auto msrc = const_cast<atomic_refcounted_string_ref *>(src); // NOLINT
  246. msrc->_begin = msrc->_end = nullptr;
  247. msrc->_state[0] = msrc->_state[1] = msrc->_state[2] = nullptr;
  248. return;
  249. }
  250. case _thunk_op::destruct:
  251. {
  252. if(dest->_msg() != nullptr)
  253. {
  254. auto count = dest->_msg()->count.fetch_sub(1, std::memory_order_release);
  255. if(count == 1)
  256. {
  257. std::atomic_thread_fence(std::memory_order_acquire);
  258. free((void *) dest->_begin); // NOLINT
  259. delete dest->_msg(); // NOLINT
  260. }
  261. }
  262. }
  263. }
  264. }
  265. public:
  266. //! Construct from a C string literal allocated using `malloc()`.
  267. explicit atomic_refcounted_string_ref(const char *str, size_type len = static_cast<size_type>(-1), void *state1 = nullptr, void *state2 = nullptr) noexcept : string_ref(str, len, new(std::nothrow) _allocated_msg, state1, state2, _refcounted_string_thunk)
  268. {
  269. if(_msg() == nullptr)
  270. {
  271. free((void *) this->_begin); // NOLINT
  272. _msg() = nullptr; // disabled
  273. this->_begin = "failed to get message from system";
  274. this->_end = strchr(this->_begin, 0);
  275. return;
  276. }
  277. }
  278. };
  279. private:
  280. unique_id_type _id;
  281. protected:
  282. /*! Use [https://www.random.org/cgi-bin/randbyte?nbytes=8&format=h](https://www.random.org/cgi-bin/randbyte?nbytes=8&format=h) to get a random 64 bit id.
  283. Do NOT make up your own value. Do NOT use zero.
  284. */
  285. constexpr explicit status_code_domain(unique_id_type id) noexcept : _id(id) {}
  286. //! No public copying at type erased level
  287. status_code_domain(const status_code_domain &) = default;
  288. //! No public moving at type erased level
  289. status_code_domain(status_code_domain &&) = default;
  290. //! No public assignment at type erased level
  291. status_code_domain &operator=(const status_code_domain &) = default;
  292. //! No public assignment at type erased level
  293. status_code_domain &operator=(status_code_domain &&) = default;
  294. //! No public destruction at type erased level
  295. ~status_code_domain() = default;
  296. public:
  297. //! True if the unique ids match.
  298. constexpr bool operator==(const status_code_domain &o) const noexcept { return _id == o._id; }
  299. //! True if the unique ids do not match.
  300. constexpr bool operator!=(const status_code_domain &o) const noexcept { return _id != o._id; }
  301. //! True if this unique is lower than the other's unique id.
  302. constexpr bool operator<(const status_code_domain &o) const noexcept { return _id < o._id; }
  303. //! Returns the unique id used to identify identical category instances.
  304. constexpr unique_id_type id() const noexcept { return _id; }
  305. //! Name of this category.
  306. virtual string_ref name() const noexcept = 0;
  307. protected:
  308. //! True if code means failure.
  309. virtual bool _do_failure(const status_code<void> &code) const noexcept = 0;
  310. //! True if code is (potentially non-transitively) equivalent to another code in another domain.
  311. virtual bool _do_equivalent(const status_code<void> &code1, const status_code<void> &code2) const noexcept = 0;
  312. //! Returns the generic code closest to this code, if any.
  313. virtual generic_code _generic_code(const status_code<void> &code) const noexcept = 0;
  314. //! Return a reference to a string textually representing a code.
  315. virtual string_ref _do_message(const status_code<void> &code) const noexcept = 0;
  316. #if defined(_CPPUNWIND) || defined(__EXCEPTIONS) || defined(BOOST_OUTCOME_STANDARDESE_IS_IN_THE_HOUSE)
  317. //! Throw a code as a C++ exception.
  318. BOOST_OUTCOME_SYSTEM_ERROR2_NORETURN virtual void _do_throw_exception(const status_code<void> &code) const = 0;
  319. #else
  320. // Keep a vtable slot for binary compatibility
  321. BOOST_OUTCOME_SYSTEM_ERROR2_NORETURN virtual void _do_throw_exception(const status_code<void> & /*code*/) const { abort(); }
  322. #endif
  323. // For a `status_code<erased<T>>` only, copy from `src` to `dst`. Default implementation uses `memcpy()`.
  324. virtual void _do_erased_copy(status_code<void> &dst, const status_code<void> &src, size_t bytes) const { memcpy(&dst, &src, bytes); } // NOLINT
  325. // For a `status_code<erased<T>>` only, destroy the erased value type. Default implementation does nothing.
  326. virtual void _do_erased_destroy(status_code<void> &code, size_t bytes) const noexcept // NOLINT
  327. {
  328. (void) code;
  329. (void) bytes;
  330. }
  331. };
  332. BOOST_OUTCOME_SYSTEM_ERROR2_NAMESPACE_END
  333. #endif