Time.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2022-2023, Sam Atkins <atkinssj@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Time.h"
  7. #include <LibWeb/CSS/Percentage.h>
  8. namespace Web::CSS {
  9. Time::Time(double value, Type type)
  10. : m_type(type)
  11. , m_value(value)
  12. {
  13. }
  14. Time Time::make_seconds(double value)
  15. {
  16. return { value, Type::S };
  17. }
  18. Time Time::percentage_of(Percentage const& percentage) const
  19. {
  20. return Time { percentage.as_fraction() * m_value, m_type };
  21. }
  22. String Time::to_string() const
  23. {
  24. return MUST(String::formatted("{}s", to_seconds()));
  25. }
  26. double Time::to_seconds() const
  27. {
  28. switch (m_type) {
  29. case Type::S:
  30. return m_value;
  31. case Type::Ms:
  32. return m_value / 1000.0;
  33. }
  34. VERIFY_NOT_REACHED();
  35. }
  36. double Time::to_milliseconds() const
  37. {
  38. switch (m_type) {
  39. case Type::S:
  40. return m_value * 1000.0;
  41. case Type::Ms:
  42. return m_value;
  43. }
  44. VERIFY_NOT_REACHED();
  45. }
  46. StringView Time::unit_name() const
  47. {
  48. switch (m_type) {
  49. case Type::S:
  50. return "s"sv;
  51. case Type::Ms:
  52. return "ms"sv;
  53. }
  54. VERIFY_NOT_REACHED();
  55. }
  56. Optional<Time::Type> Time::unit_from_name(StringView name)
  57. {
  58. if (name.equals_ignoring_ascii_case("s"sv)) {
  59. return Type::S;
  60. } else if (name.equals_ignoring_ascii_case("ms"sv)) {
  61. return Type::Ms;
  62. }
  63. return {};
  64. }
  65. }