Skip to main content

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; compressing contents if possible.
19    Shrink,
20
21    /// Fill the minimum amount of space based on the intrinsic size of the
22    /// element; normally defined by its contents.
23    Fit,
24
25    /// Fill a fixed amount of space
26    Fixed(f32),
27}
28
29impl Length {
30    /// Returns the _fill factor_ of the [`Length`].
31    ///
32    /// The _fill factor_ is a relative unit describing how much of the
33    /// remaining space should be filled when compared to other elements. It
34    /// is only meant to be used by layout engines.
35    pub fn fill_factor(&self) -> u16 {
36        match self {
37            Length::Fill => 1,
38            Length::FillPortion(factor) => *factor,
39            Length::Shrink | Length::Fit | Length::Fixed(_) => 0,
40        }
41    }
42
43    /// Returns `true` if the [`Length`] is either [`Length::Fill`] or
44    /// [`Length::FillPortion`].
45    pub fn is_fill(&self) -> bool {
46        self.fill_factor() != 0
47    }
48
49    /// Returns `true` if the [`Length`] is [`Fit`](Self::Fit).
50    pub fn is_fit(&self) -> bool {
51        matches!(self, Self::Fit)
52    }
53
54    /// Returns the "fluid" variant of the [`Length`].
55    ///
56    /// Specifically:
57    /// - [`Length::Shrink`] if [`Length::Shrink`] or [`Length::Fixed`].
58    /// - [`Length::Fill`] otherwise.
59    pub fn fluid(&self) -> Self {
60        match self {
61            Length::Fill | Length::FillPortion(_) => Length::Fill,
62            Length::Shrink | Length::Fit | Length::Fixed(_) => Length::Shrink,
63        }
64    }
65
66    /// Adapts the [`Length`] so it can contain the other [`Length`] and
67    /// match its fluidity.
68    #[inline]
69    pub fn enclose(self, other: Length) -> Self {
70        match (self, other) {
71            (Length::Fit, Length::Fill | Length::FillPortion(_)) => other,
72            _ => self,
73        }
74    }
75}
76
77impl From<Pixels> for Length {
78    fn from(amount: Pixels) -> Self {
79        Length::Fixed(f32::from(amount))
80    }
81}
82
83impl From<f32> for Length {
84    fn from(amount: f32) -> Self {
85        Length::Fixed(amount)
86    }
87}
88
89impl From<u32> for Length {
90    fn from(units: u32) -> Self {
91        Length::Fixed(units as f32)
92    }
93}