Time.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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(float value, Type type)
  15. : m_type(type)
  16. , m_value(value)
  17. {
  18. }
  19. Time Time::make_seconds(float 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("{}{}", m_value, unit_name());
  30. }
  31. float 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.0f;
  38. }
  39. VERIFY_NOT_REACHED();
  40. }
  41. StringView Time::unit_name() const
  42. {
  43. switch (m_type) {
  44. case Type::S:
  45. return "s"sv;
  46. case Type::Ms:
  47. return "ms"sv;
  48. }
  49. VERIFY_NOT_REACHED();
  50. }
  51. Optional<Time::Type> Time::unit_from_name(StringView name)
  52. {
  53. if (name.equals_ignoring_ascii_case("s"sv)) {
  54. return Type::S;
  55. } else if (name.equals_ignoring_ascii_case("ms"sv)) {
  56. return Type::Ms;
  57. }
  58. return {};
  59. }
  60. }