Error.hpp 2.4 KB

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