Value.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * Copyright (c) 2021-2022, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/ByteString.h>
  8. #include <AK/Format.h>
  9. #include <AK/RefPtr.h>
  10. #include <AK/Variant.h>
  11. #include <LibPDF/Forward.h>
  12. #include <LibPDF/Object.h>
  13. #include <LibPDF/Reference.h>
  14. namespace PDF {
  15. class Value : public Variant<Empty, nullptr_t, bool, int, float, Reference, NonnullRefPtr<Object>> {
  16. public:
  17. using Variant::Variant;
  18. template<IsObject T>
  19. Value(RefPtr<T> const& refptr)
  20. : Variant(nullptr)
  21. {
  22. if (refptr)
  23. set<NonnullRefPtr<Object>>(*refptr);
  24. }
  25. template<IsObject T>
  26. Value(NonnullRefPtr<T> const& refptr)
  27. requires(!IsSame<Object, T>)
  28. : Variant(nullptr)
  29. {
  30. set<NonnullRefPtr<Object>>(*refptr);
  31. }
  32. [[nodiscard]] ByteString to_byte_string(int indent = 0) const;
  33. [[nodiscard]] ALWAYS_INLINE bool has_number() const { return has<int>() || has<float>(); }
  34. [[nodiscard]] ALWAYS_INLINE bool has_u32() const
  35. {
  36. return has<int>() && get<int>() >= 0;
  37. }
  38. [[nodiscard]] ALWAYS_INLINE bool has_u16() const
  39. {
  40. return has<int>() && get<int>() >= 0 && get<int>() < 65536;
  41. }
  42. [[nodiscard]] ALWAYS_INLINE u32 get_u32() const
  43. {
  44. VERIFY(has_u32());
  45. return get<int>();
  46. }
  47. [[nodiscard]] ALWAYS_INLINE u16 get_u16() const
  48. {
  49. VERIFY(has_u16());
  50. return get<int>();
  51. }
  52. [[nodiscard]] ALWAYS_INLINE int to_int() const
  53. {
  54. if (has<int>())
  55. return get<int>();
  56. return static_cast<int>(get<float>());
  57. }
  58. [[nodiscard]] ALWAYS_INLINE float to_float() const
  59. {
  60. if (has<float>())
  61. return get<float>();
  62. return static_cast<float>(get<int>());
  63. }
  64. [[nodiscard]] ALWAYS_INLINE u32 as_ref_index() const
  65. {
  66. return get<Reference>().as_ref_index();
  67. }
  68. [[nodiscard]] ALWAYS_INLINE u32 as_ref_generation_index() const
  69. {
  70. return get<Reference>().as_ref_generation_index();
  71. }
  72. };
  73. }
  74. namespace AK {
  75. template<>
  76. struct Formatter<PDF::Value> : Formatter<StringView> {
  77. ErrorOr<void> format(FormatBuilder& builder, PDF::Value const& value)
  78. {
  79. return Formatter<StringView>::format(builder, value.to_byte_string());
  80. }
  81. };
  82. }