iced_core/
length.rs

1use crate::Pixels;
2
3/// The strategy used to fill space in a specific dimension.
4#[derive(Debug, Clone, Copy, PartialEq)]
5pub enum Length {
6    /// Fill all the remaining space
7    Fill,
8
9    /// Fill a portion of the remaining space relative to other elements.
10    ///
11    /// Let's say we have two elements: one with `FillPortion(2)` and one with
12    /// `FillPortion(3)`. The first will get 2 portions of the available space,
13    /// while the second one would get 3.
14    ///
15    /// `Length::Fill` is equivalent to `Length::FillPortion(1)`.
16    FillPortion(u16),
17
18    /// Fill the least amount of space
19    Shrink,
20
21    /// Fill a fixed amount of space
22    Fixed(f32),
23}
24
25impl Length {
26    /// Returns the _fill factor_ of the [`Length`].
27    ///
28    /// The _fill factor_ is a relative unit describing how much of the
29    /// remaining space should be filled when compared to other elements. It
30    /// is only meant to be used by layout engines.
31    pub fn fill_factor(&self) -> u16 {
32        match self {
33            Length::Fill => 1,
34            Length::FillPortion(factor) => *factor,
35            Length::Shrink => 0,
36            Length::Fixed(_) => 0,
37        }
38    }
39
40    /// Returns `true` iff the [`Length`] is either [`Length::Fill`] or
41    // [`Length::FillPortion`].
42    pub fn is_fill(&self) -> bool {
43        self.fill_factor() != 0
44    }
45
46    /// Returns the "fluid" variant of the [`Length`].
47    ///
48    /// Specifically:
49    /// - [`Length::Shrink`] if [`Length::Shrink`] or [`Length::Fixed`].
50    /// - [`Length::Fill`] otherwise.
51    pub fn fluid(&self) -> Self {
52        match self {
53            Length::Fill | Length::FillPortion(_) => Length::Fill,
54            Length::Shrink | Length::Fixed(_) => Length::Shrink,
55        }
56    }
57
58    /// Adapts the [`Length`] so it can contain the other [`Length`] and
59    /// match its fluidity.
60    pub fn enclose(self, other: Length) -> Self {
61        match (self, other) {
62            (Length::Shrink, Length::Fill | Length::FillPortion(_)) => other,
63            _ => self,
64        }
65    }
66}
67
68impl From<Pixels> for Length {
69    fn from(amount: Pixels) -> Self {
70        Length::Fixed(f32::from(amount))
71    }
72}
73
74impl From<f32> for Length {
75    fn from(amount: f32) -> Self {
76        Length::Fixed(amount)
77    }
78}
79
80impl From<u32> for Length {
81    fn from(units: u32) -> Self {
82        Length::Fixed(units as f32)
83    }
84}