1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
//! CSS time values.

use super::angle::impl_try_from_angle;
use super::calc::Calc;
use super::number::CSSNumber;
use crate::error::{ParserError, PrinterError};
use crate::printer::Printer;
use crate::traits::private::AddInternal;
use crate::traits::{impl_op, Map, Op, Parse, Sign, ToCss, Zero};
use cssparser::*;

/// A CSS [`<time>`](https://www.w3.org/TR/css-values-4/#time) value, in either
/// seconds or milliseconds.
///
/// Time values may be explicit or computed by `calc()`, but are always stored and serialized
/// as their computed value.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum Time {
  /// A time in seconds.
  Seconds(CSSNumber),
  /// A time in milliseconds.
  Milliseconds(CSSNumber),
}

impl Time {
  /// Returns the time in milliseconds.
  pub fn to_ms(&self) -> CSSNumber {
    match self {
      Time::Seconds(s) => s * 1000.0,
      Time::Milliseconds(ms) => *ms,
    }
  }
}

impl Zero for Time {
  fn zero() -> Self {
    Time::Milliseconds(0.0)
  }

  fn is_zero(&self) -> bool {
    match self {
      Time::Seconds(s) => s.is_zero(),
      Time::Milliseconds(s) => s.is_zero(),
    }
  }
}

impl<'i> Parse<'i> for Time {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    match input.try_parse(Calc::parse) {
      Ok(Calc::Value(v)) => return Ok(*v),
      // Time is always compatible, so they will always compute to a value.
      Ok(_) => return Err(input.new_custom_error(ParserError::InvalidValue)),
      _ => {}
    }

    let location = input.current_source_location();
    match *input.next()? {
      Token::Dimension { value, ref unit, .. } => {
        match_ignore_ascii_case! { unit,
          "s" => Ok(Time::Seconds(value)),
          "ms" => Ok(Time::Milliseconds(value)),
          _ => Err(location.new_unexpected_token_error(Token::Ident(unit.clone())))
        }
      }
      ref t => Err(location.new_unexpected_token_error(t.clone())),
    }
  }
}

impl ToCss for Time {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    // 0.1s is shorter than 100ms
    // anything smaller is longer
    match self {
      Time::Seconds(s) => {
        if *s > 0.0 && *s < 0.1 {
          (*s * 1000.0).to_css(dest)?;
          dest.write_str("ms")
        } else {
          s.to_css(dest)?;
          dest.write_str("s")
        }
      }
      Time::Milliseconds(ms) => {
        if *ms == 0.0 || *ms >= 100.0 {
          (*ms / 1000.0).to_css(dest)?;
          dest.write_str("s")
        } else {
          ms.to_css(dest)?;
          dest.write_str("ms")
        }
      }
    }
  }
}

impl std::convert::Into<Calc<Time>> for Time {
  fn into(self) -> Calc<Time> {
    Calc::Value(Box::new(self))
  }
}

impl std::convert::From<Calc<Time>> for Time {
  fn from(calc: Calc<Time>) -> Time {
    match calc {
      Calc::Value(v) => *v,
      _ => unreachable!(),
    }
  }
}

impl std::ops::Mul<f32> for Time {
  type Output = Self;

  fn mul(self, other: f32) -> Time {
    match self {
      Time::Seconds(t) => Time::Seconds(t * other),
      Time::Milliseconds(t) => Time::Milliseconds(t * other),
    }
  }
}

impl AddInternal for Time {
  fn add(self, other: Self) -> Self {
    self + other
  }
}

impl std::cmp::PartialOrd<Time> for Time {
  fn partial_cmp(&self, other: &Time) -> Option<std::cmp::Ordering> {
    self.to_ms().partial_cmp(&other.to_ms())
  }
}

impl Op for Time {
  fn op<F: FnOnce(f32, f32) -> f32>(&self, to: &Self, op: F) -> Self {
    match (self, to) {
      (Time::Seconds(a), Time::Seconds(b)) => Time::Seconds(op(*a, *b)),
      (Time::Milliseconds(a), Time::Milliseconds(b)) => Time::Milliseconds(op(*a, *b)),
      (Time::Seconds(a), Time::Milliseconds(b)) => Time::Seconds(op(*a, b / 1000.0)),
      (Time::Milliseconds(a), Time::Seconds(b)) => Time::Milliseconds(op(*a, b * 1000.0)),
    }
  }

  fn op_to<T, F: FnOnce(f32, f32) -> T>(&self, rhs: &Self, op: F) -> T {
    match (self, rhs) {
      (Time::Seconds(a), Time::Seconds(b)) => op(*a, *b),
      (Time::Milliseconds(a), Time::Milliseconds(b)) => op(*a, *b),
      (Time::Seconds(a), Time::Milliseconds(b)) => op(*a, b / 1000.0),
      (Time::Milliseconds(a), Time::Seconds(b)) => op(*a, b * 1000.0),
    }
  }
}

impl Map for Time {
  fn map<F: FnOnce(f32) -> f32>(&self, op: F) -> Self {
    match self {
      Time::Seconds(t) => Time::Seconds(op(*t)),
      Time::Milliseconds(t) => Time::Milliseconds(op(*t)),
    }
  }
}

impl Sign for Time {
  fn sign(&self) -> f32 {
    match self {
      Time::Seconds(v) | Time::Milliseconds(v) => v.sign(),
    }
  }
}

impl_op!(Time, std::ops::Rem, rem);
impl_op!(Time, std::ops::Add, add);

impl_try_from_angle!(Time);