Object.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) 2021, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Debug.h>
  8. #include <AK/FlyString.h>
  9. #include <AK/Format.h>
  10. #include <AK/RefCounted.h>
  11. #include <AK/SourceLocation.h>
  12. #include <LibPDF/Forward.h>
  13. #include <LibPDF/Value.h>
  14. namespace PDF {
  15. class Object : public RefCounted<Object> {
  16. public:
  17. virtual ~Object() = default;
  18. [[nodiscard]] ALWAYS_INLINE u32 generation_index() const { return m_generation_index; }
  19. ALWAYS_INLINE void set_generation_index(u32 generation_index) { m_generation_index = generation_index; }
  20. #define DEFINE_ID(_, name) \
  21. virtual bool is_##name() const { return false; }
  22. ENUMERATE_OBJECT_TYPES(DEFINE_ID)
  23. #undef DEFINE_ID
  24. virtual const char* type_name() const = 0;
  25. virtual String to_string(int indent) const = 0;
  26. private:
  27. u32 m_generation_index { 0 };
  28. };
  29. template<IsObject To, IsObject From>
  30. [[nodiscard]] ALWAYS_INLINE static NonnullRefPtr<To> object_cast(NonnullRefPtr<From> obj
  31. #ifdef PDF_DEBUG
  32. ,
  33. SourceLocation loc = SourceLocation::current()
  34. #endif
  35. )
  36. {
  37. #ifdef PDF_DEBUG
  38. # define ENUMERATE_TYPES(class_name, snake_name) \
  39. if constexpr (IsSame<To, class_name>) { \
  40. if (!obj->is_##snake_name()) { \
  41. dbgln("{} invalid cast from type {} to type " #snake_name, loc, obj->type_name()); \
  42. } \
  43. }
  44. ENUMERATE_OBJECT_TYPES(ENUMERATE_TYPES)
  45. # undef ENUMERATE_TYPES
  46. #endif
  47. return static_ptr_cast<To>(obj);
  48. }
  49. }
  50. namespace AK {
  51. template<PDF::IsObject T>
  52. struct Formatter<T> : Formatter<StringView> {
  53. ErrorOr<void> format(FormatBuilder& builder, T const& object)
  54. {
  55. return Formatter<StringView>::format(builder, object.to_string(0));
  56. }
  57. };
  58. template<PDF::IsObject T>
  59. struct Formatter<NonnullRefPtr<T>> : Formatter<T> {
  60. ErrorOr<void> format(FormatBuilder& builder, NonnullRefPtr<T> const& object)
  61. {
  62. return Formatter<T>::format(builder, *object);
  63. }
  64. };
  65. }