css_ast/types/
opacity_value.rs

1use super::prelude::*;
2use crate::Percentage;
3
4#[derive(IntoCursor, Peek, Parse, ToCursors, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize))]
6#[cfg_attr(feature = "visitable", derive(csskit_derives::Visitable), visit(self))]
7pub enum OpacityValue {
8	Number(#[in_range(0.0..=1.0)] T![Number]),
9	Percent(#[in_range(0.0..=100.0)] Percentage),
10}
11
12impl OpacityValue {
13	#[allow(non_upper_case_globals)]
14	pub const Zero: OpacityValue = OpacityValue::Number(<T![Number]>::NUMBER_ZERO);
15}
16
17impl From<OpacityValue> for i32 {
18	fn from(value: OpacityValue) -> Self {
19		match value {
20			OpacityValue::Number(t) => t.into(),
21			OpacityValue::Percent(t) => {
22				let f: f32 = t.into();
23				f as i32
24			}
25		}
26	}
27}
28
29impl From<OpacityValue> for f32 {
30	fn from(value: OpacityValue) -> Self {
31		match value {
32			OpacityValue::Number(t) => t.into(),
33			OpacityValue::Percent(t) => t.into(),
34		}
35	}
36}
37
38#[cfg(test)]
39mod tests {
40	use super::*;
41	use crate::CssAtomSet;
42	use css_parse::{assert_parse, assert_parse_error};
43
44	#[test]
45	fn size_test() {
46		assert_eq!(std::mem::size_of::<OpacityValue>(), 16);
47	}
48
49	#[test]
50	fn test_writes() {
51		assert_parse!(CssAtomSet::ATOMS, OpacityValue, "0.1");
52		assert_parse!(CssAtomSet::ATOMS, OpacityValue, "1");
53		assert_parse!(CssAtomSet::ATOMS, OpacityValue, "50%");
54	}
55
56	#[test]
57	fn test_errors() {
58		assert_parse_error!(CssAtomSet::ATOMS, OpacityValue, "20");
59		assert_parse_error!(CssAtomSet::ATOMS, OpacityValue, "1000%");
60	}
61
62	// #[cfg(feature = "serde")]
63	// #[test]
64	// fn test_serializes() {
65	// 	assert_json!(OpacityValue, "0.1", {
66	// 		"node": [0, 3],
67	// 		"start": 0,
68	// 		"end": 5
69	// 	});
70	// }
71}