Skip to main content

egui_pop_fit/
size.rs

1//! Slot sizes, counted in twelfths of the base unit.
2
3use core::fmt;
4
5/// Twelfths in one base unit. 12 is the least common multiple of 2, 3 and 4,
6/// so every allowed size is a whole number of twelfths.
7pub const TWELFTHS_PER_UNIT: u32 = 12;
8
9/// The allowed sizes below one unit, in twelfths: ¼, ⅓, ½, ⅔, ¾.
10const FRACTIONS: [u32; 5] = [3, 4, 6, 8, 9];
11
12/// Half a unit, in twelfths: the hysteresis band.
13pub(crate) const HALF_UNIT: u32 = TWELFTHS_PER_UNIT / 2;
14
15/// A standard slot size along one axis: ¼, ⅓, ½, ⅔, ¾ of the base unit, or a
16/// whole number of units.
17///
18/// The value is stored in twelfths of the unit, so sums stay exact. A `Size`
19/// can only hold an allowed value.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
21#[cfg_attr(
22    feature = "serde",
23    derive(serde::Serialize, serde::Deserialize),
24    serde(try_from = "u32", into = "u32")
25)]
26pub struct Size(u32);
27
28impl Size {
29    /// A quarter of the unit.
30    pub const QUARTER: Size = Size(3);
31    /// A third of the unit.
32    pub const THIRD: Size = Size(4);
33    /// Half the unit.
34    pub const HALF: Size = Size(6);
35    /// Two thirds of the unit.
36    pub const TWO_THIRDS: Size = Size(8);
37    /// Three quarters of the unit.
38    pub const THREE_QUARTERS: Size = Size(9);
39    /// One whole unit.
40    pub const ONE: Size = Size(12);
41
42    /// `n` whole units. `n` is raised to 1 if zero.
43    pub const fn units(n: u32) -> Size {
44        let n = if n == 0 { 1 } else { n };
45        Size(n.saturating_mul(TWELFTHS_PER_UNIT) / TWELFTHS_PER_UNIT * TWELFTHS_PER_UNIT)
46    }
47
48    /// The size of `twelfths` twelfths, if it is an allowed size.
49    pub fn from_twelfths(twelfths: u32) -> Option<Size> {
50        is_allowed(twelfths).then_some(Size(twelfths))
51    }
52
53    /// The size in twelfths of the unit.
54    pub const fn twelfths(self) -> u32 {
55        self.0
56    }
57
58    /// The next larger allowed size.
59    pub fn next_step(self) -> Size {
60        next_step(self.0).map_or(self, Size)
61    }
62
63    /// The next smaller allowed size, if any.
64    pub fn prev_step(self) -> Option<Size> {
65        prev_step(self.0).map(Size)
66    }
67}
68
69impl fmt::Display for Size {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match self.0 {
72            3 => f.write_str("1/4"),
73            4 => f.write_str("1/3"),
74            6 => f.write_str("1/2"),
75            8 => f.write_str("2/3"),
76            9 => f.write_str("3/4"),
77            t => write!(f, "{}", t / TWELFTHS_PER_UNIT),
78        }
79    }
80}
81
82/// The error of converting a number of twelfths that is not an allowed size.
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub struct InvalidSize(pub u32);
85
86impl fmt::Display for InvalidSize {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        write!(f, "{} twelfths is not an allowed slot size", self.0)
89    }
90}
91
92impl std::error::Error for InvalidSize {}
93
94impl TryFrom<u32> for Size {
95    type Error = InvalidSize;
96    fn try_from(twelfths: u32) -> Result<Size, InvalidSize> {
97        Size::from_twelfths(twelfths).ok_or(InvalidSize(twelfths))
98    }
99}
100
101impl From<Size> for u32 {
102    fn from(size: Size) -> u32 {
103        size.0
104    }
105}
106
107/// Whether `t` twelfths is an allowed size.
108pub(crate) fn is_allowed(t: u32) -> bool {
109    FRACTIONS.contains(&t) || (t > 0 && t.is_multiple_of(TWELFTHS_PER_UNIT))
110}
111
112/// The smallest allowed size above `t`.
113pub(crate) fn next_step(t: u32) -> Option<u32> {
114    if t < TWELFTHS_PER_UNIT {
115        FRACTIONS
116            .iter()
117            .copied()
118            .find(|&f| f > t)
119            .or(Some(TWELFTHS_PER_UNIT))
120    } else {
121        (t / TWELFTHS_PER_UNIT + 1).checked_mul(TWELFTHS_PER_UNIT)
122    }
123}
124
125/// The largest allowed size below `t`.
126pub(crate) fn prev_step(t: u32) -> Option<u32> {
127    floor_step(t.checked_sub(1)?)
128}
129
130/// The largest allowed size at most `t`.
131pub(crate) fn floor_step(t: u32) -> Option<u32> {
132    if t >= TWELFTHS_PER_UNIT {
133        Some(t / TWELFTHS_PER_UNIT * TWELFTHS_PER_UNIT)
134    } else {
135        FRACTIONS.iter().copied().rev().find(|&f| f <= t)
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn ladder() {
145        let mut s = Size::QUARTER;
146        let mut seen = vec![s.twelfths()];
147        for _ in 0..7 {
148            s = s.next_step();
149            seen.push(s.twelfths());
150        }
151        assert_eq!(seen, [3, 4, 6, 8, 9, 12, 24, 36]);
152        assert_eq!(Size::units(2).prev_step(), Some(Size::ONE));
153        assert_eq!(Size::ONE.prev_step(), Some(Size::THREE_QUARTERS));
154        assert_eq!(Size::QUARTER.prev_step(), None);
155    }
156
157    #[test]
158    fn allowed_only() {
159        assert!(Size::from_twelfths(5).is_none());
160        assert!(Size::from_twelfths(13).is_none());
161        assert!(Size::from_twelfths(0).is_none());
162        assert_eq!(Size::from_twelfths(36), Some(Size::units(3)));
163        assert_eq!(Size::units(0), Size::ONE);
164        assert_eq!(floor_step(23), Some(12));
165        assert_eq!(floor_step(7), Some(6));
166        assert_eq!(floor_step(2), None);
167        assert_eq!(Size::TWO_THIRDS.to_string(), "2/3");
168    }
169}