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 #[must_use]
29 pub fn from_values(values: &[f32]) -> Option<Self> {
30 match *values {
31 [all] => Some(Padding::uniform(all)),
32 [vertical, horizontal] => Some(Padding::new(vertical, horizontal, vertical, horizontal)),
33 [top, horizontal, bottom] => Some(Padding::new(top, horizontal, bottom, horizontal)),
34 [top, right, bottom, left] => Some(Padding::new(top, right, bottom, left)),
35 _ => None,
36 }
37 }
38
39 #[must_use]
41 pub fn is_nonzero(&self) -> bool {
42 self.top != 0.0 || self.right != 0.0 || self.bottom != 0.0 || self.left != 0.0
43 }
44
45 #[must_use]
47 pub(crate) fn to_array(self) -> [f64; 4] {
48 [f64::from(self.top), f64::from(self.right), f64::from(self.bottom), f64::from(self.left)]
49 }
50
51 #[must_use]
53 pub fn serialize(&self) -> Value {
54 Value::Array(self.to_array().iter().map(|v| Value::Double(*v)).collect())
55 }
56}
57
58impl std::ops::Mul<f32> for Padding {
60 type Output = Padding;
61 fn mul(self, scale: f32) -> Padding {
62 Padding::new(self.top * scale, self.right * scale, self.bottom * scale, self.left * scale)
63 }
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69 use crate::conversion::{Convertible, Error};
70 use crate::expression::{EvaluationContext, Functions};
71 use crate::feature::Value as FeatureValue;
72 use crate::property::convert::convert_property_value;
73 use crate::property::expression::PropertyExpression;
74 use crate::tests::util::{StubGeometryTileFeature, property_map};
75
76 #[test]
77 fn values_expand_in_css_order() {
78 assert_eq!(Padding::from_values(&[1.0]), Some(Padding::uniform(1.0)));
79 assert_eq!(Padding::from_values(&[1.0, 2.0]), Some(Padding::new(1.0, 2.0, 1.0, 2.0)));
80 assert_eq!(Padding::from_values(&[1.0, 2.0, 3.0]), Some(Padding::new(1.0, 2.0, 3.0, 2.0)));
81 assert_eq!(Padding::from_values(&[1.0, 2.0, 3.0, 4.0]), Some(Padding::new(1.0, 2.0, 3.0, 4.0)));
82 assert!(Padding::from_values(&[]).is_none());
83 assert!(Padding::from_values(&[1.0; 5]).is_none());
84 }
85
86 #[test]
87 fn scales_each_side_and_is_nonzero_when_any_side_is() {
88 assert_eq!(Padding::new(1.0, 2.0, 3.0, 4.0) * 2.0, Padding::new(2.0, 4.0, 6.0, 8.0));
89 assert!(!Padding::uniform(0.0).is_nonzero());
90 assert!(Padding { left: 1.0, ..Padding::default() }.is_nonzero());
91 }
92
93 fn expression(json: &str) -> PropertyExpression<Padding> {
96 let value: serde_json::Value = serde_json::from_str(json).unwrap();
97 let mut error = Error::default();
98 let converted = convert_property_value::<Padding>(
99 &Convertible::from(&value),
100 &mut error,
101 true,
102 false,
103 true,
104 &Functions::with_builtins(),
105 );
106 converted.unwrap_or_else(|| panic!("{json}: {}", error.message)).as_expression().unwrap().clone()
107 }
108
109 #[test]
110 fn interpolates_each_side_after_expanding() {
111 let to_padding = r#"["interpolate", ["linear"], ["zoom"], 0, ["to-padding", 0], 1, ["to-padding", ["literal", [8, 16, -32]]]]"#;
112 let function = r#"{"type": "exponential", "stops": [[1, 2], [11, [2, 5, 2, 7]]]}"#;
113 for (json, zoom, padding) in [
114 (to_padding, 0.5, Padding::new(4.0, 8.0, -16.0, 8.0)),
115 (function, 0.0, Padding::uniform(2.0)),
116 (function, 5.0, Padding::new(2.0, 3.2, 2.0, 4.0)),
117 (function, 11.0, Padding::new(2.0, 5.0, 2.0, 7.0)),
118 ] {
119 assert_eq!(
120 expression(json).evaluate(&EvaluationContext::new(zoom), Padding::default()),
121 padding,
122 "{json} at {zoom}"
123 );
124 }
125 }
126
127 #[test]
131 fn identity_function_expands_the_feature_value_or_takes_its_default() {
132 let expression = expression(r#"{"type": "identity", "property": "foo", "default": [3, 7, 9, 11]}"#);
133 let numbers = |values: &[f64]| FeatureValue::Array(values.iter().map(|&v| FeatureValue::Double(v)).collect());
134 for (properties, padding) in [
135 (vec![("foo", numbers(&[2.0, 4.0, 6.0]))], Padding::new(2.0, 4.0, 6.0, 4.0)),
136 (vec![("foo", FeatureValue::Double(3.0))], Padding::uniform(3.0)),
137 (vec![("foo", FeatureValue::String("wide".to_owned()))], Padding::new(3.0, 7.0, 9.0, 11.0)),
138 (vec![], Padding::new(3.0, 7.0, 9.0, 11.0)),
139 ] {
140 let feature = StubGeometryTileFeature::new(property_map(&properties));
141 assert_eq!(
142 expression.evaluate(&EvaluationContext::with_zoom_feature(0.0, Some(&feature)), Padding::default()),
143 padding,
144 "{properties:?}"
145 );
146 }
147 }
148
149 #[test]
152 fn style_json_converts_in_css_order() {
153 use crate::conversion::{Converter, Convertible, Error};
154
155 let convert = |json: &str| {
156 let mut error = Error::default();
157 let value: serde_json::Value = serde_json::from_str(json).unwrap();
158 <Padding as Converter>::convert(&Convertible::from(&value), &mut error).ok_or(error.message)
159 };
160 for (json, expected) in [
161 ("3", Padding::new(3.0, 3.0, 3.0, 3.0)),
162 ("[3.5, 4.5]", Padding::new(3.5, 4.5, 3.5, 4.5)),
163 ("[2, 3, 1]", Padding::new(2.0, 3.0, 1.0, 3.0)),
164 ("[-2.5, -3.5, -1.0, -0.5]", Padding::new(-2.5, -3.5, -1.0, -0.5)),
165 ] {
166 assert_eq!(Ok(expected), convert(json), "{json}");
167 }
168 let error = "value must be a number or an array of numbers (between 1 and 4 elements)";
169 for json in ["null", "false", "[]", "[1, 2, 3, 4, 5]", "[true, false]", "[null]", r#"{"foo": 1}"#] {
170 assert_eq!(Err(error.to_owned()), convert(json), "{json}");
171 }
172 }
173}