Skip to main content

css_ast/units/
time.rs

1use super::prelude::*;
2
3/// <https://drafts.csswg.org/css-values/#time>
4///
5/// ```text,ignore
6/// <time> = <dimension-token>
7/// ```
8#[derive(IntoCursor, Parse, Peek, ToCursors, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
9#[cfg_attr(feature = "serde", derive(serde::Serialize), serde())]
10#[cfg_attr(feature = "visitable", derive(csskit_derives::Visitable), visit(self))]
11#[derive(csskit_derives::NodeWithMetadata)]
12#[metadata(node_kinds = Dimension)]
13pub enum Time {
14	#[atom(CssAtomSet::Ms)]
15	Ms(T![Dimension]),
16	#[atom(CssAtomSet::S)]
17	S(T![Dimension]),
18}
19
20impl Time {
21	pub fn as_seconds(&self) -> f32 {
22		match self {
23			Self::Ms(f) => Into::<f32>::into(*f) / 1000.0,
24			Self::S(f) => (*f).into(),
25		}
26	}
27}
28
29impl From<Time> for f32 {
30	fn from(val: Time) -> Self {
31		match val {
32			Time::Ms(f) => f.into(),
33			Time::S(f) => f.into(),
34		}
35	}
36}
37
38impl ToNumberValue for Time {
39	fn to_number_value(&self) -> Option<f32> {
40		Some((*self).into())
41	}
42}
43
44#[cfg(test)]
45mod tests {
46	use super::*;
47	use crate::CssAtomSet;
48	use css_parse::{assert_parse, assert_parse_error};
49
50	#[test]
51	fn size_test() {
52		assert_eq!(std::mem::size_of::<Time>(), 16);
53	}
54
55	#[test]
56	fn test_writes() {
57		assert_parse!(CssAtomSet::ATOMS, Time, "0s");
58		assert_parse!(CssAtomSet::ATOMS, Time, "0ms");
59		assert_parse!(CssAtomSet::ATOMS, Time, "1s");
60		assert_parse!(CssAtomSet::ATOMS, Time, "100ms");
61	}
62
63	#[test]
64	fn test_errors() {
65		assert_parse_error!(CssAtomSet::ATOMS, Time, "0");
66		assert_parse_error!(CssAtomSet::ATOMS, Time, "1");
67		assert_parse_error!(CssAtomSet::ATOMS, Time, "foo");
68	}
69}