Value.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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/Format.h>
  8. #include <AK/RefPtr.h>
  9. #include <AK/String.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, std::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) requires(!IsSame<Object, T>)
  27. : Variant(nullptr)
  28. {
  29. set<NonnullRefPtr<Object>>(*refptr);
  30. }
  31. [[nodiscard]] String to_string(int indent = 0) const;
  32. [[nodiscard]] ALWAYS_INLINE bool has_number() const { return has<int>() || has<float>(); }
  33. [[nodiscard]] ALWAYS_INLINE bool has_u32() const
  34. {
  35. return has<int>() && get<int>() >= 0;
  36. }
  37. [[nodiscard]] ALWAYS_INLINE bool has_u16() const
  38. {
  39. return has<int>() && get<int>() >= 0 && get<int>() < 65536;
  40. }
  41. [[nodiscard]] ALWAYS_INLINE u32 get_u32() const
  42. {
  43. VERIFY(has_u32());
  44. return get<int>();
  45. }
  46. [[nodiscard]] ALWAYS_INLINE u16 get_u16() const
  47. {
  48. VERIFY(has_u16());
  49. return get<int>();
  50. }
  51. [[nodiscard]] ALWAYS_INLINE int to_int() const
  52. {
  53. if (has<int>())
  54. return get<int>();
  55. return static_cast<int>(get<float>());
  56. }
  57. [[nodiscard]] ALWAYS_INLINE float to_float() const
  58. {
  59. if (has<float>())
  60. return get<float>();
  61. return static_cast<float>(get<int>());
  62. }
  63. [[nodiscard]] ALWAYS_INLINE u32 as_ref_index() const
  64. {
  65. return get<Reference>().as_ref_index();
  66. }
  67. [[nodiscard]] ALWAYS_INLINE u32 as_ref_generation_index() const
  68. {
  69. return get<Reference>().as_ref_generation_index();
  70. }
  71. };
  72. }
  73. namespace AK {
  74. template<>
  75. struct Formatter<PDF::Value> : Formatter<StringView> {
  76. ErrorOr<void> format(FormatBuilder& builder, PDF::Value const& value)
  77. {
  78. return Formatter<StringView>::format(builder, value.to_string());
  79. }
  80. };
  81. }