Frequency.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (c) 2022-2023, Sam Atkins <atkinssj@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Frequency.h"
  7. #include <LibWeb/CSS/Percentage.h>
  8. #include <LibWeb/CSS/StyleValues/CSSMathValue.h>
  9. namespace Web::CSS {
  10. Frequency::Frequency(double value, Type type)
  11. : m_type(type)
  12. , m_value(value)
  13. {
  14. }
  15. Frequency Frequency::make_hertz(double value)
  16. {
  17. return { value, Type::Hz };
  18. }
  19. Frequency Frequency::percentage_of(Percentage const& percentage) const
  20. {
  21. return Frequency { percentage.as_fraction() * m_value, m_type };
  22. }
  23. String Frequency::to_string() const
  24. {
  25. return MUST(String::formatted("{}hz", to_hertz()));
  26. }
  27. double Frequency::to_hertz() const
  28. {
  29. switch (m_type) {
  30. case Type::Hz:
  31. return m_value;
  32. case Type::kHz:
  33. return m_value * 1000;
  34. }
  35. VERIFY_NOT_REACHED();
  36. }
  37. StringView Frequency::unit_name() const
  38. {
  39. switch (m_type) {
  40. case Type::Hz:
  41. return "hz"sv;
  42. case Type::kHz:
  43. return "khz"sv;
  44. }
  45. VERIFY_NOT_REACHED();
  46. }
  47. Optional<Frequency::Type> Frequency::unit_from_name(StringView name)
  48. {
  49. if (name.equals_ignoring_ascii_case("hz"sv)) {
  50. return Type::Hz;
  51. } else if (name.equals_ignoring_ascii_case("khz"sv)) {
  52. return Type::kHz;
  53. }
  54. return {};
  55. }
  56. Frequency Frequency::resolve_calculated(NonnullRefPtr<CSSMathValue> const& calculated, Layout::Node const&, Frequency const& reference_value)
  57. {
  58. return calculated->resolve_frequency_percentage(reference_value).value();
  59. }
  60. }