LoaderError.h 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (c) 2021, kleines Filmröllchen <filmroellchen@serenityos.org>.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/DeprecatedFlyString.h>
  8. #include <AK/Error.h>
  9. #include <errno.h>
  10. namespace Audio {
  11. struct LoaderError {
  12. enum class Category : u32 {
  13. // The error category is unknown.
  14. Unknown = 0,
  15. IO,
  16. // The read file doesn't follow the file format.
  17. Format,
  18. // Equivalent to an ASSERT(), except non-crashing.
  19. Internal,
  20. // The loader encountered something in the format that is not yet implemented.
  21. Unimplemented,
  22. };
  23. Category category { Category::Unknown };
  24. // Binary index: where in the file the error occurred.
  25. size_t index { 0 };
  26. DeprecatedFlyString description { ByteString::empty() };
  27. constexpr LoaderError() = default;
  28. LoaderError(Category category, size_t index, DeprecatedFlyString description)
  29. : category(category)
  30. , index(index)
  31. , description(move(description))
  32. {
  33. }
  34. LoaderError(DeprecatedFlyString description)
  35. : description(move(description))
  36. {
  37. }
  38. LoaderError(Category category, DeprecatedFlyString description)
  39. : category(category)
  40. , description(move(description))
  41. {
  42. }
  43. LoaderError(LoaderError&) = default;
  44. LoaderError(LoaderError&&) = default;
  45. LoaderError(Error&& error)
  46. {
  47. if (error.is_errno()) {
  48. auto code = error.code();
  49. description = ByteString::formatted("{} ({})", strerror(code), code);
  50. if (code == EBADF || code == EBUSY || code == EEXIST || code == EIO || code == EISDIR || code == ENOENT || code == ENOMEM || code == EPIPE)
  51. category = Category::IO;
  52. } else {
  53. description = error.string_literal();
  54. }
  55. }
  56. };
  57. }
  58. namespace AK {
  59. template<>
  60. struct Formatter<Audio::LoaderError> : Formatter<FormatString> {
  61. ErrorOr<void> format(FormatBuilder& builder, Audio::LoaderError const& error)
  62. {
  63. StringView category;
  64. switch (error.category) {
  65. case Audio::LoaderError::Category::Unknown:
  66. category = "Unknown"sv;
  67. break;
  68. case Audio::LoaderError::Category::IO:
  69. category = "I/O"sv;
  70. break;
  71. case Audio::LoaderError::Category::Format:
  72. category = "Format"sv;
  73. break;
  74. case Audio::LoaderError::Category::Internal:
  75. category = "Internal"sv;
  76. break;
  77. case Audio::LoaderError::Category::Unimplemented:
  78. category = "Unimplemented"sv;
  79. break;
  80. }
  81. return Formatter<FormatString>::format(builder, "{} error: {} (at {})"sv, category, error.description, error.index);
  82. }
  83. };
  84. }