Time.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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(int value, Type type)
  10. : m_type(type)
  11. , m_value(value)
  12. {
  13. }
  14. Time::Time(double value, Type type)
  15. : m_type(type)
  16. , m_value(value)
  17. {
  18. }
  19. Time Time::make_seconds(double value)
  20. {
  21. return { value, Type::S };
  22. }
  23. Time Time::percentage_of(Percentage const& percentage) const
  24. {
  25. return Time { percentage.as_fraction() * m_value, m_type };
  26. }
  27. ErrorOr<String> Time::to_string() const
  28. {
  29. return String::formatted("{}s", to_seconds());
  30. }
  31. double Time::to_seconds() const
  32. {
  33. switch (m_type) {
  34. case Type::S:
  35. return m_value;
  36. case Type::Ms:
  37. return m_value / 1000.0;
  38. }
  39. VERIFY_NOT_REACHED();
  40. }
  41. double Time::to_milliseconds() const
  42. {
  43. switch (m_type) {
  44. case Type::S:
  45. return m_value * 1000.0;
  46. case Type::Ms:
  47. return m_value;
  48. }
  49. VERIFY_NOT_REACHED();
  50. }
  51. StringView Time::unit_name() const
  52. {
  53. switch (m_type) {
  54. case Type::S:
  55. return "s"sv;
  56. case Type::Ms:
  57. return "ms"sv;
  58. }
  59. VERIFY_NOT_REACHED();
  60. }
  61. Optional<Time::Type> Time::unit_from_name(StringView name)
  62. {
  63. if (name.equals_ignoring_ascii_case("s"sv)) {
  64. return Type::S;
  65. } else if (name.equals_ignoring_ascii_case("ms"sv)) {
  66. return Type::Ms;
  67. }
  68. return {};
  69. }
  70. }