DecoderError.h 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright (c) 2022, Gregory Bertilson <zaggy1024@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Error.h>
  8. #include <AK/Format.h>
  9. #include <AK/SourceLocation.h>
  10. #include <AK/String.h>
  11. #include <errno.h>
  12. namespace Video {
  13. struct DecoderError;
  14. template<typename T>
  15. using DecoderErrorOr = ErrorOr<T, DecoderError>;
  16. enum class DecoderErrorCategory : u32 {
  17. Unknown,
  18. IO,
  19. Memory,
  20. // The input is corrupted.
  21. Corrupted,
  22. // Invalid call.
  23. Invalid,
  24. // The input uses features that are not yet implemented.
  25. NotImplemented,
  26. };
  27. struct DecoderError {
  28. public:
  29. static DecoderError with_description(DecoderErrorCategory category, StringView description)
  30. {
  31. return DecoderError(category, description);
  32. }
  33. template<typename... Parameters>
  34. static DecoderError format(DecoderErrorCategory category, CheckedFormatString<Parameters...>&& format_string, Parameters const&... parameters)
  35. {
  36. AK::VariadicFormatParams variadic_format_params { parameters... };
  37. return DecoderError::with_description(category, String::vformatted(format_string.view(), variadic_format_params));
  38. }
  39. static DecoderError corrupted(StringView description, SourceLocation location = SourceLocation::current())
  40. {
  41. return DecoderError::format(DecoderErrorCategory::Corrupted, "{}: {}", location, description);
  42. }
  43. static DecoderError not_implemented(SourceLocation location = SourceLocation::current())
  44. {
  45. return DecoderError::format(DecoderErrorCategory::NotImplemented, "{} is not implemented", location.function_name());
  46. }
  47. DecoderErrorCategory category() { return m_category; }
  48. StringView description() { return m_description; }
  49. StringView string_literal() { return m_description; }
  50. private:
  51. DecoderError(DecoderErrorCategory category, String description)
  52. : m_category(category)
  53. , m_description(move(description))
  54. {
  55. }
  56. DecoderErrorCategory m_category { DecoderErrorCategory::Unknown };
  57. String m_description;
  58. };
  59. #define DECODER_TRY(category, expression) \
  60. ({ \
  61. auto _result = ((expression)); \
  62. if (_result.is_error()) [[unlikely]] { \
  63. auto _error_string = _result.release_error().string_literal(); \
  64. return DecoderError::format( \
  65. ((category)), "{}: {}", \
  66. SourceLocation::current(), _error_string); \
  67. } \
  68. _result.release_value(); \
  69. })
  70. #define DECODER_TRY_ALLOC(expression) DECODER_TRY(DecoderErrorCategory::Memory, expression)
  71. }