Frequency.cpp 1.3 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. namespace Web::CSS {
  9. Frequency::Frequency(int value, Type type)
  10. : m_type(type)
  11. , m_value(value)
  12. {
  13. }
  14. Frequency::Frequency(float value, Type type)
  15. : m_type(type)
  16. , m_value(value)
  17. {
  18. }
  19. Frequency Frequency::make_hertz(float value)
  20. {
  21. return { value, Type::Hz };
  22. }
  23. Frequency Frequency::percentage_of(Percentage const& percentage) const
  24. {
  25. return Frequency { percentage.as_fraction() * m_value, m_type };
  26. }
  27. ErrorOr<String> Frequency::to_string() const
  28. {
  29. return String::formatted("{}{}", m_value, unit_name());
  30. }
  31. float Frequency::to_hertz() const
  32. {
  33. switch (m_type) {
  34. case Type::Hz:
  35. return m_value;
  36. case Type::kHz:
  37. return m_value * 1000;
  38. }
  39. VERIFY_NOT_REACHED();
  40. }
  41. StringView Frequency::unit_name() const
  42. {
  43. switch (m_type) {
  44. case Type::Hz:
  45. return "hz"sv;
  46. case Type::kHz:
  47. return "khz"sv;
  48. }
  49. VERIFY_NOT_REACHED();
  50. }
  51. Optional<Frequency::Type> Frequency::unit_from_name(StringView name)
  52. {
  53. if (name.equals_ignoring_ascii_case("hz"sv)) {
  54. return Type::Hz;
  55. } else if (name.equals_ignoring_ascii_case("khz"sv)) {
  56. return Type::kHz;
  57. }
  58. return {};
  59. }
  60. }