Skip to main content

taffy/util/
resolve.rs

1//! Helper trait to calculate dimensions during layout resolution
2
3use crate::geometry::{Rect, Size};
4use crate::style::{Dimension, LengthPercentage, LengthPercentageAuto};
5use crate::style_helpers::TaffyZero;
6use crate::CompactLength;
7
8/// Trait to encapsulate behaviour where we need to resolve from a
9/// potentially context-dependent size or dimension into
10/// a context-independent size or dimension.
11///
12/// Will return a `None` if it unable to resolve.
13pub trait MaybeResolve<In, Out> {
14    /// Resolve a dimension that might be dependent on a context, with `None` as fallback value
15    fn maybe_resolve(self, context: In, calc: impl Fn(*const (), f32) -> f32) -> Out;
16}
17
18/// Trait to encapsulate behaviour where we need to resolve from a
19/// potentially context-dependent size or dimension into
20/// a context-independent size or dimension.
21///
22/// Will return a default value if it unable to resolve.
23pub trait ResolveOrZero<TContext, TOutput: TaffyZero> {
24    /// Resolve a dimension that might be dependent on a context, with a default fallback value
25    fn resolve_or_zero(self, context: TContext, calc: impl Fn(*const (), f32) -> f32) -> TOutput;
26}
27
28impl MaybeResolve<Option<f32>, Option<f32>> for LengthPercentage {
29    /// Converts the given [`LengthPercentage`] into an absolute length
30    /// Can return `None`
31    fn maybe_resolve(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> Option<f32> {
32        match self.0.tag() {
33            CompactLength::LENGTH_TAG => Some(self.0.value()),
34            CompactLength::PERCENT_TAG => context.map(|dim| dim * self.0.value()),
35            #[cfg(feature = "calc")]
36            _ if self.0.is_calc() => context.map(|dim| calc(self.0.calc_value(), dim)),
37            _ => unreachable!(),
38        }
39    }
40}
41
42impl MaybeResolve<Option<f32>, Option<f32>> for LengthPercentageAuto {
43    /// Converts the given [`LengthPercentageAuto`] into an absolute length
44    /// Can return `None`
45    fn maybe_resolve(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> Option<f32> {
46        match self.0.tag() {
47            CompactLength::AUTO_TAG => None,
48            CompactLength::LENGTH_TAG => Some(self.0.value()),
49            CompactLength::PERCENT_TAG => context.map(|dim| dim * self.0.value()),
50            #[cfg(feature = "calc")]
51            _ if self.0.is_calc() => context.map(|dim| calc(self.0.calc_value(), dim)),
52            _ => unreachable!(),
53        }
54    }
55}
56
57impl MaybeResolve<Option<f32>, Option<f32>> for Dimension {
58    /// Converts the given [`Dimension`] into an absolute length
59    ///
60    /// Can return `None`
61    fn maybe_resolve(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> Option<f32> {
62        match self.0.tag() {
63            CompactLength::AUTO_TAG => None,
64            // The content keyword is only valid for flex-basis. In any other context it behaves as auto.
65            CompactLength::CONTENT_TAG => None,
66            CompactLength::LENGTH_TAG => Some(self.0.value()),
67            CompactLength::PERCENT_TAG => context.map(|dim| dim * self.0.value()),
68            #[cfg(feature = "calc")]
69            _ if self.0.is_calc() => context.map(|dim| calc(self.0.calc_value(), dim)),
70            // Intrinsic sizing keywords cannot be resolved to a definite size out of context.
71            // Layout algorithms that support them must handle them explicitly.
72            _ if self.0.is_sizing_keyword() => None,
73            _ => unreachable!(),
74        }
75    }
76}
77
78// Generic implementation of MaybeResolve for f32 context where MaybeResolve is implemented
79// for Option<f32> context
80impl<T: MaybeResolve<Option<f32>, Option<f32>>> MaybeResolve<f32, Option<f32>> for T {
81    /// Converts the given MaybeResolve value into an absolute length
82    /// Can return `None`
83    fn maybe_resolve(self, context: f32, calc: impl Fn(*const (), f32) -> f32) -> Option<f32> {
84        self.maybe_resolve(Some(context), calc)
85    }
86}
87
88// Generic MaybeResolve for Size
89impl<In, Out, T: MaybeResolve<In, Out>> MaybeResolve<Size<In>, Size<Out>> for Size<T> {
90    /// Converts any `parent`-relative values for size into an absolute size
91    fn maybe_resolve(self, context: Size<In>, calc: impl Fn(*const (), f32) -> f32) -> Size<Out> {
92        Size {
93            width: self.width.maybe_resolve(context.width, &calc),
94            height: self.height.maybe_resolve(context.height, &calc),
95        }
96    }
97}
98
99impl ResolveOrZero<Option<f32>, f32> for LengthPercentage {
100    /// Will return a default value of result is evaluated to `None`
101    fn resolve_or_zero(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> f32 {
102        self.maybe_resolve(context, calc).unwrap_or(0.0)
103    }
104}
105
106impl ResolveOrZero<Option<f32>, f32> for LengthPercentageAuto {
107    /// Will return a default value of result is evaluated to `None`
108    fn resolve_or_zero(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> f32 {
109        self.maybe_resolve(context, calc).unwrap_or(0.0)
110    }
111}
112
113impl ResolveOrZero<Option<f32>, f32> for Dimension {
114    /// Will return a default value of result is evaluated to `None`
115    fn resolve_or_zero(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> f32 {
116        self.maybe_resolve(context, calc).unwrap_or(0.0)
117    }
118}
119
120// Generic ResolveOrZero for Size
121impl<In, Out: TaffyZero, T: ResolveOrZero<In, Out>> ResolveOrZero<Size<In>, Size<Out>> for Size<T> {
122    /// Converts any `parent`-relative values for size into an absolute size
123    fn resolve_or_zero(self, context: Size<In>, calc: impl Fn(*const (), f32) -> f32) -> Size<Out> {
124        Size {
125            width: self.width.resolve_or_zero(context.width, &calc),
126            height: self.height.resolve_or_zero(context.height, &calc),
127        }
128    }
129}
130
131// Generic ResolveOrZero for resolving Rect against Size
132impl<In: Copy, Out: TaffyZero, T: ResolveOrZero<In, Out>> ResolveOrZero<Size<In>, Rect<Out>> for Rect<T> {
133    /// Converts any `parent`-relative values for Rect into an absolute Rect
134    fn resolve_or_zero(self, context: Size<In>, calc: impl Fn(*const (), f32) -> f32) -> Rect<Out> {
135        Rect {
136            left: self.left.resolve_or_zero(context.width, &calc),
137            right: self.right.resolve_or_zero(context.width, &calc),
138            top: self.top.resolve_or_zero(context.height, &calc),
139            bottom: self.bottom.resolve_or_zero(context.height, &calc),
140        }
141    }
142}
143
144// Generic ResolveOrZero for resolving Rect against Option
145impl<Out: TaffyZero, T: ResolveOrZero<Option<f32>, Out>> ResolveOrZero<Option<f32>, Rect<Out>> for Rect<T> {
146    /// Converts any `parent`-relative values for Rect into an absolute Rect
147    fn resolve_or_zero(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> Rect<Out> {
148        Rect {
149            left: self.left.resolve_or_zero(context, &calc),
150            right: self.right.resolve_or_zero(context, &calc),
151            top: self.top.resolve_or_zero(context, &calc),
152            bottom: self.bottom.resolve_or_zero(context, &calc),
153        }
154    }
155}
156
157// Generic ResolveOrZero for resolving Rect against f32
158impl<Out: TaffyZero, T: ResolveOrZero<f32, Out>> ResolveOrZero<f32, Rect<Out>> for Rect<T> {
159    /// Converts any `parent`-relative values for Rect into an absolute Rect
160    fn resolve_or_zero(self, context: f32, calc: impl Fn(*const (), f32) -> f32) -> Rect<Out> {
161        Rect {
162            left: self.left.resolve_or_zero(context, &calc),
163            right: self.right.resolve_or_zero(context, &calc),
164            top: self.top.resolve_or_zero(context, &calc),
165            bottom: self.bottom.resolve_or_zero(context, &calc),
166        }
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::{MaybeResolve, ResolveOrZero};
173    use crate::style_helpers::TaffyZero;
174    use core::fmt::Debug;
175
176    // MaybeResolve test runner
177    fn mr_case<Lhs, Rhs, Out>(input: Lhs, context: Rhs, expected: Out)
178    where
179        Lhs: MaybeResolve<Rhs, Out>,
180        Out: PartialEq + Debug,
181    {
182        assert_eq!(input.maybe_resolve(context, |_, _| 42.42), expected);
183    }
184
185    // ResolveOrZero test runner
186    fn roz_case<Lhs, Rhs, Out>(input: Lhs, context: Rhs, expected: Out)
187    where
188        Lhs: ResolveOrZero<Rhs, Out>,
189        Out: PartialEq + Debug + TaffyZero,
190    {
191        assert_eq!(input.resolve_or_zero(context, |_, _| 42.42), expected);
192    }
193
194    mod maybe_resolve_dimension {
195        use super::mr_case;
196        use crate::style::Dimension;
197        use crate::style_helpers::*;
198
199        /// `Dimension::Auto` should always return `None`
200        ///
201        /// The parent / context should not affect the outcome.
202        #[test]
203        fn resolve_auto() {
204            mr_case(Dimension::AUTO, None, None);
205            mr_case(Dimension::AUTO, Some(5.0), None);
206            mr_case(Dimension::AUTO, Some(-5.0), None);
207            mr_case(Dimension::AUTO, Some(0.), None);
208        }
209
210        /// `Dimension::Length` should always return `Some(f32)`
211        /// where the f32 value is the inner absolute length.
212        ///
213        /// The parent / context should not affect the outcome.
214        #[test]
215        fn resolve_length() {
216            mr_case(Dimension::from_length(1.0), None, Some(1.0));
217            mr_case(Dimension::from_length(1.0), Some(5.0), Some(1.0));
218            mr_case(Dimension::from_length(1.0), Some(-5.0), Some(1.0));
219            mr_case(Dimension::from_length(1.0), Some(0.), Some(1.0));
220        }
221
222        /// `Dimension::Percent` should return `None` if context is  `None`.
223        /// Otherwise it should return `Some(f32)`
224        /// where the f32 value is the inner value of the percent * context value.
225        ///
226        /// The parent / context __should__ affect the outcome.
227        #[test]
228        fn resolve_percent() {
229            mr_case(Dimension::from_percent(1.0), None, None);
230            mr_case(Dimension::from_percent(1.0), Some(5.0), Some(5.0));
231            mr_case(Dimension::from_percent(1.0), Some(-5.0), Some(-5.0));
232            mr_case(Dimension::from_percent(1.0), Some(50.0), Some(50.0));
233        }
234    }
235
236    mod maybe_resolve_size_dimension {
237        use super::mr_case;
238        use crate::geometry::Size;
239        use crate::style::Dimension;
240
241        /// Size<Dimension::Auto> should always return Size<None>
242        ///
243        /// The parent / context should not affect the outcome.
244        #[test]
245        fn maybe_resolve_auto() {
246            mr_case(Size::<Dimension>::auto(), Size::NONE, Size::NONE);
247            mr_case(Size::<Dimension>::auto(), Size::new(5.0, 5.0), Size::NONE);
248            mr_case(Size::<Dimension>::auto(), Size::new(-5.0, -5.0), Size::NONE);
249            mr_case(Size::<Dimension>::auto(), Size::new(0.0, 0.0), Size::NONE);
250        }
251
252        /// Size<Dimension::Length> should always return a Size<Some(f32)>
253        /// where the f32 values are the absolute length.
254        ///
255        /// The parent / context should not affect the outcome.
256        #[test]
257        fn maybe_resolve_length() {
258            mr_case(Size::from_lengths(5.0, 5.0), Size::NONE, Size::new(5.0, 5.0));
259            mr_case(Size::from_lengths(5.0, 5.0), Size::new(5.0, 5.0), Size::new(5.0, 5.0));
260            mr_case(Size::from_lengths(5.0, 5.0), Size::new(-5.0, -5.0), Size::new(5.0, 5.0));
261            mr_case(Size::from_lengths(5.0, 5.0), Size::new(0.0, 0.0), Size::new(5.0, 5.0));
262        }
263
264        /// `Size<Dimension::Percent>` should return `Size<None>` if context is `Size<None>`.
265        /// Otherwise it should return `Size<Some(f32)>`
266        /// where the f32 value is the inner value of the percent * context value.
267        ///
268        /// The context __should__ affect the outcome.
269        #[test]
270        fn maybe_resolve_percent() {
271            mr_case(Size::from_percent(5.0, 5.0), Size::NONE, Size::NONE);
272            mr_case(Size::from_percent(5.0, 5.0), Size::new(5.0, 5.0), Size::new(25.0, 25.0));
273            mr_case(Size::from_percent(5.0, 5.0), Size::new(-5.0, -5.0), Size::new(-25.0, -25.0));
274            mr_case(Size::from_percent(5.0, 5.0), Size::new(0.0, 0.0), Size::new(0.0, 0.0));
275        }
276    }
277
278    mod resolve_or_zero_dimension_to_option_f32 {
279        use super::roz_case;
280        use crate::style::Dimension;
281        use crate::style_helpers::*;
282
283        #[test]
284        fn resolve_or_zero_auto() {
285            roz_case(Dimension::AUTO, None, 0.0);
286            roz_case(Dimension::AUTO, Some(5.0), 0.0);
287            roz_case(Dimension::AUTO, Some(-5.0), 0.0);
288            roz_case(Dimension::AUTO, Some(0.0), 0.0);
289        }
290        #[test]
291        fn resolve_or_zero_length() {
292            roz_case(Dimension::from_length(5.0), None, 5.0);
293            roz_case(Dimension::from_length(5.0), Some(5.0), 5.0);
294            roz_case(Dimension::from_length(5.0), Some(-5.0), 5.0);
295            roz_case(Dimension::from_length(5.0), Some(0.0), 5.0);
296        }
297        #[test]
298        fn resolve_or_zero_percent() {
299            roz_case(Dimension::from_percent(5.0), None, 0.0);
300            roz_case(Dimension::from_percent(5.0), Some(5.0), 25.0);
301            roz_case(Dimension::from_percent(5.0), Some(-5.0), -25.0);
302            roz_case(Dimension::from_percent(5.0), Some(0.0), 0.0);
303        }
304    }
305
306    mod resolve_or_zero_rect_dimension_to_rect {
307        use super::roz_case;
308        use crate::geometry::{Rect, Size};
309        use crate::style::Dimension;
310
311        #[test]
312        fn resolve_or_zero_auto() {
313            roz_case(Rect::<Dimension>::auto(), Size::NONE, Rect::zero());
314            roz_case(Rect::<Dimension>::auto(), Size::new(5.0, 5.0), Rect::zero());
315            roz_case(Rect::<Dimension>::auto(), Size::new(-5.0, -5.0), Rect::zero());
316            roz_case(Rect::<Dimension>::auto(), Size::new(0.0, 0.0), Rect::zero());
317        }
318
319        #[test]
320        fn resolve_or_zero_length() {
321            roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Size::NONE, Rect::new(5.0, 5.0, 5.0, 5.0));
322            roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Size::new(5.0, 5.0), Rect::new(5.0, 5.0, 5.0, 5.0));
323            roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Size::new(-5.0, -5.0), Rect::new(5.0, 5.0, 5.0, 5.0));
324            roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Size::new(0.0, 0.0), Rect::new(5.0, 5.0, 5.0, 5.0));
325        }
326
327        #[test]
328        fn resolve_or_zero_percent() {
329            roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Size::NONE, Rect::zero());
330            roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Size::new(5.0, 5.0), Rect::new(25.0, 25.0, 25.0, 25.0));
331            roz_case(
332                Rect::from_percent(5.0, 5.0, 5.0, 5.0),
333                Size::new(-5.0, -5.0),
334                Rect::new(-25.0, -25.0, -25.0, -25.0),
335            );
336            roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Size::new(0.0, 0.0), Rect::zero());
337        }
338    }
339
340    mod resolve_or_zero_rect_dimension_to_rect_f32_via_option {
341        use super::roz_case;
342        use crate::geometry::Rect;
343        use crate::style::Dimension;
344
345        #[test]
346        fn resolve_or_zero_auto() {
347            roz_case(Rect::<Dimension>::auto(), None, Rect::zero());
348            roz_case(Rect::<Dimension>::auto(), Some(5.0), Rect::zero());
349            roz_case(Rect::<Dimension>::auto(), Some(-5.0), Rect::zero());
350            roz_case(Rect::<Dimension>::auto(), Some(0.0), Rect::zero());
351        }
352
353        #[test]
354        fn resolve_or_zero_length() {
355            roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), None, Rect::new(5.0, 5.0, 5.0, 5.0));
356            roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Some(5.0), Rect::new(5.0, 5.0, 5.0, 5.0));
357            roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Some(-5.0), Rect::new(5.0, 5.0, 5.0, 5.0));
358            roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Some(0.0), Rect::new(5.0, 5.0, 5.0, 5.0));
359        }
360
361        #[test]
362        fn resolve_or_zero_percent() {
363            roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), None, Rect::zero());
364            roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Some(5.0), Rect::new(25.0, 25.0, 25.0, 25.0));
365            roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Some(-5.0), Rect::new(-25.0, -25.0, -25.0, -25.0));
366            roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Some(0.0), Rect::zero());
367        }
368    }
369}