1use crate::feature::Value;
4
5#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
7pub struct Padding {
8 pub top: f32,
9 pub right: f32,
10 pub bottom: f32,
11 pub left: f32,
12}
13
14impl Padding {
15 #[must_use]
16 pub const fn new(top: f32, right: f32, bottom: f32, left: f32) -> Self {
17 Padding { top, right, bottom, left }
18 }
19
20 #[must_use]
22 pub const fn uniform(value: f32) -> Self {
23 Padding::new(value, value, value, value)
24 }
25
26 pub fn from_values(values: &[f32]) -> Result<Self, String> {
29 match values.len() {
30 1 => Ok(Padding::uniform(values[0])),
31 2 => Ok(Padding::new(values[0], values[1], values[0], values[1])),
32 3 => Ok(Padding::new(values[0], values[1], values[2], values[1])),
33 4 => Ok(Padding::new(values[0], values[1], values[2], values[3])),
34 _ => Err("Padding must have between 1 and 4 elements".to_owned()),
35 }
36 }
37
38 #[must_use]
40 pub fn is_nonzero(&self) -> bool {
41 self.top != 0.0 || self.right != 0.0 || self.bottom != 0.0 || self.left != 0.0
42 }
43
44 #[must_use]
46 pub(crate) fn to_array(self) -> [f64; 4] {
47 [f64::from(self.top), f64::from(self.right), f64::from(self.bottom), f64::from(self.left)]
48 }
49
50 #[must_use]
52 pub fn serialize(&self) -> Value {
53 Value::Array(self.to_array().iter().map(|v| Value::Double(*v)).collect())
54 }
55}
56
57impl std::ops::Mul<f32> for Padding {
59 type Output = Padding;
60 fn mul(self, scale: f32) -> Padding {
61 Padding::new(self.top * scale, self.right * scale, self.bottom * scale, self.left * scale)
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68
69 #[test]
70 fn css_order() {
71 assert_eq!(Padding::from_values(&[1.0, 2.0, 3.0]), Ok(Padding::new(1.0, 2.0, 3.0, 2.0)));
72 assert_eq!(Padding::from_values(&[1.0, 2.0]), Ok(Padding::new(1.0, 2.0, 1.0, 2.0)));
73 assert!(Padding::from_values(&[]).is_err());
74 }
75}