Value.h 2.1 KB

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