Number.h 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/String.h>
  8. #include <AK/Types.h>
  9. #include <math.h>
  10. namespace Web::CSS {
  11. class Number {
  12. public:
  13. enum class Type {
  14. Number,
  15. IntegerWithExplicitSign, // This only exists for the nightmarish An+B parsing algorithm
  16. Integer
  17. };
  18. Number()
  19. : m_value(0)
  20. , m_type(Type::Number)
  21. {
  22. }
  23. Number(Type type, float value)
  24. : m_value(value)
  25. , m_type(type)
  26. {
  27. }
  28. Type type() const { return m_type; }
  29. float value() const { return m_value; }
  30. i64 integer_value() const
  31. {
  32. // https://www.w3.org/TR/css-values-4/#numeric-types
  33. // When a value cannot be explicitly supported due to range/precision limitations, it must be converted
  34. // to the closest value supported by the implementation, but how the implementation defines "closest"
  35. // is explicitly undefined as well.
  36. return llroundf(m_value);
  37. }
  38. bool is_integer() const { return m_type == Type::Integer || m_type == Type::IntegerWithExplicitSign; }
  39. bool is_integer_with_explicit_sign() const { return m_type == Type::IntegerWithExplicitSign; }
  40. Number operator+(Number const& other) const
  41. {
  42. if (is_integer() && other.is_integer())
  43. return { Type::Integer, m_value + other.m_value };
  44. return { Type::Number, m_value + other.m_value };
  45. }
  46. Number operator-(Number const& other) const
  47. {
  48. if (is_integer() && other.is_integer())
  49. return { Type::Integer, m_value - other.m_value };
  50. return { Type::Number, m_value - other.m_value };
  51. }
  52. Number operator*(Number const& other) const
  53. {
  54. if (is_integer() && other.is_integer())
  55. return { Type::Integer, m_value * other.m_value };
  56. return { Type::Number, m_value * other.m_value };
  57. }
  58. Number operator/(Number const& other) const
  59. {
  60. return { Type::Number, m_value / other.m_value };
  61. }
  62. ErrorOr<String> to_string() const
  63. {
  64. if (m_type == Type::IntegerWithExplicitSign)
  65. return String::formatted("{:+}", m_value);
  66. return String::number(m_value);
  67. }
  68. bool operator==(Number const& other) const
  69. {
  70. return m_type == other.m_type && m_value == other.m_value;
  71. }
  72. private:
  73. float m_value { 0 };
  74. Type m_type;
  75. };
  76. }
  77. template<>
  78. struct AK::Formatter<Web::CSS::Number> : Formatter<StringView> {
  79. ErrorOr<void> format(FormatBuilder& builder, Web::CSS::Number const& number)
  80. {
  81. return Formatter<StringView>::format(builder, TRY(number.to_string()));
  82. }
  83. };