Error.hpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #ifndef CORE_ERROR_HPP
  2. #define CORE_ERROR_HPP
  3. #include "core/utils/Check.hpp"
  4. #include "core/utils/Types.hpp"
  5. namespace Core {
  6. struct Error {
  7. using Code = unsigned int;
  8. static_assert(sizeof(Code) >= 4, "error code too small");
  9. Code code;
  10. constexpr Error(Code c) : code(c) {
  11. }
  12. bool check() const {
  13. return code != 0;
  14. }
  15. bool contains(Error e) const {
  16. return code & e.code;
  17. }
  18. bool operator==(Error e) const {
  19. return code == e.code;
  20. }
  21. bool operator!=(Error e) const {
  22. return !(*this == e);
  23. }
  24. Error& operator|=(Error e) {
  25. code |= e.code;
  26. return *this;
  27. }
  28. Error operator|(Error e) const {
  29. e |= *this;
  30. return e;
  31. }
  32. };
  33. namespace ErrorCode {
  34. static constexpr Error NONE = 0;
  35. static constexpr Error ERROR = 1 << 0;
  36. static constexpr Error NEGATIVE_ARGUMENT = 1 << 1;
  37. static constexpr Error CAPACITY_REACHED = 1 << 2;
  38. static constexpr Error BLOCKED_STDOUT = 1 << 3;
  39. static constexpr Error OUT_OF_MEMORY = 1 << 4;
  40. static constexpr Error INVALID_CHAR = 1 << 5;
  41. static constexpr Error NOT_FOUND = 1 << 6;
  42. static constexpr Error INVALID_STATE = 1 << 7;
  43. static constexpr Error INVALID_INDEX = 1 << 8;
  44. static constexpr Error INVALID_ARGUMENT = 1 << 9;
  45. static constexpr Error TIME_NOT_AVAILABLE = 1 << 10;
  46. static constexpr Error SLEEP_INTERRUPTED = 1 << 11;
  47. static constexpr Error THREAD_ERROR = 1 << 12;
  48. static constexpr Error MUTEX_ERROR = 1 << 13;
  49. static constexpr Error EXISTING_KEY = 1 << 14;
  50. static constexpr Error CANNOT_OPEN_FILE = 1 << 15;
  51. static constexpr Error END_OF_FILE = 1 << 16;
  52. }
  53. size_t toString(Error e, char* buffer, size_t size);
  54. inline bool checkError(Error& storage, Error e) {
  55. return (storage = e).check();
  56. }
  57. #define CORE_RETURN_ERROR(checked) \
  58. { \
  59. Core::Error error = Core::ErrorCode::NONE; \
  60. if(checkError(error, checked)) [[unlikely]] { \
  61. return error; \
  62. } \
  63. }
  64. }
  65. #endif