Skip to main content

css_ast/units/
int.rs

1use super::prelude::*;
2
3#[node]
4#[derive(IntoCursor, ToSpan, SemanticEq, ToCursors, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(transparent))]
6#[cfg_attr(feature = "visitable", derive(csskit_derives::Visitable), visit(skip))]
7#[derive(csskit_derives::NodeWithMetadata)]
8pub struct CSSInt(T![Number]);
9
10impl CSSInt {
11	#[allow(non_upper_case_globals)]
12	pub const Zero: CSSInt = CSSInt(<T![Number]>::ZERO);
13
14	pub fn preserve_sign(self) -> Self {
15		CSSInt(self.0.preserve_sign())
16	}
17}
18
19impl From<CSSInt> for i32 {
20	fn from(value: CSSInt) -> Self {
21		value.0.into()
22	}
23}
24
25impl From<CSSInt> for f32 {
26	fn from(value: CSSInt) -> Self {
27		value.0.into()
28	}
29}
30
31impl ToNumberValue for CSSInt {
32	fn to_number_value(&self) -> Option<f32> {
33		Some(self.0.into())
34	}
35}
36
37impl ToNormalisedValue for CSSInt {
38	fn to_normalised_value(&self) -> Option<f32> {
39		self.to_number_value()
40	}
41}
42
43impl<'a> Peek<'a> for CSSInt {
44	const PEEK_KINDSET: KindSet = KindSet::new(&[Kind::Number]);
45
46	#[inline(always)]
47	fn peek<I>(p: &Parser<'a, I>, c: Cursor) -> bool
48	where
49		I: Iterator<Item = Cursor> + Clone,
50	{
51		<T![Number]>::peek(p, c) && c.token().is_int()
52	}
53}
54
55impl<'a> Parse<'a> for CSSInt {
56	fn parse<I>(p: &mut Parser<'a, I>) -> ParserResult<Self>
57	where
58		I: Iterator<Item = Cursor> + Clone,
59	{
60		if p.peek::<Self>() {
61			p.parse::<T![Number]>().map(Self)
62		} else {
63			Err(Diagnostic::new(p.next(), Diagnostic::unexpected))?
64		}
65	}
66}
67
68#[cfg(test)]
69mod tests {
70	use super::*;
71	use crate::CssAtomSet;
72	use css_parse::assert_parse;
73
74	#[test]
75	fn test_writes() {
76		assert_parse!(CssAtomSet::ATOMS, CSSInt, "0");
77		assert_parse!(CssAtomSet::ATOMS, CSSInt, "999999");
78	}
79}