Error.hpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. operator Code() const {
  33. return code;
  34. }
  35. };
  36. namespace ErrorCode {
  37. static constexpr Error NONE = 0;
  38. static constexpr Error ERROR = 1 << 0;
  39. static constexpr Error NEGATIVE_ARGUMENT = 1 << 1;
  40. static constexpr Error CAPACITY_REACHED = 1 << 2;
  41. static constexpr Error BLOCKED_STDOUT = 1 << 3;
  42. static constexpr Error OUT_OF_MEMORY = 1 << 4;
  43. static constexpr Error INVALID_CHAR = 1 << 5;
  44. static constexpr Error NOT_FOUND = 1 << 6;
  45. static constexpr Error INVALID_STATE = 1 << 7;
  46. static constexpr Error INVALID_INDEX = 1 << 8;
  47. static constexpr Error INVALID_ARGUMENT = 1 << 9;
  48. static constexpr Error TIME_NOT_AVAILABLE = 1 << 10;
  49. static constexpr Error SLEEP_INTERRUPTED = 1 << 11;
  50. static constexpr Error THREAD_ERROR = 1 << 12;
  51. static constexpr Error MUTEX_ERROR = 1 << 13;
  52. static constexpr Error EXISTING_KEY = 1 << 14;
  53. static constexpr Error CANNOT_OPEN_FILE = 1 << 15;
  54. static constexpr Error END_OF_FILE = 1 << 16;
  55. }
  56. CError toString(Error e, char* buffer, size_t size);
  57. inline bool checkError(Error& storage, Error e) {
  58. return (storage = e).check();
  59. }
  60. #define CORE_RETURN_ERROR(checked) \
  61. { \
  62. Core::Error error = Core::ErrorCode::NONE; \
  63. if(checkError(error, checked)) [[unlikely]] { \
  64. return error; \
  65. } \
  66. }
  67. }
  68. #endif