makepad_stitch/
limits.rs

1use crate::decode::{Decode, DecodeError, Decoder};
2
3/// A size range.
4#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
5pub struct Limits {
6    pub min: u32,
7    pub max: Option<u32>,
8}
9
10impl Limits {
11    /// Returns `true` if this [`Limits`] is valid within the range `0..=limit`.
12    ///
13    /// A [`Limits`] is valid within the range `0..=limit` if its minimum is not greater than
14    /// `limit` and its maximum, if it exists, is neither less than its minimum nor greater than
15    /// `limit`.
16    pub fn is_valid(self, limit: u32) -> bool {
17        if self.min > limit {
18            return false;
19        }
20        if self.max.map_or(false, |max| max < self.min || max > limit) {
21            return false;
22        }
23        true
24    }
25
26    /// Returns `true` if this [`Limits`] is a sublimit of the given [`Limits`].
27    ///
28    /// A [`Limits`] is a sublimit of another [`Limits`] if its minimum is not less than the
29    /// other's, and its maximum, if it exists, is not greater than the other's.
30    pub fn is_sublimit_of(self, other: Self) -> bool {
31        if self.min < other.min {
32            return false;
33        }
34        if let Some(other_max) = other.max {
35            let Some(self_max) = self.max else {
36                return false;
37            };
38            if self_max > other_max {
39                return false;
40            }
41        }
42        true
43    }
44}
45
46impl Decode for Limits {
47    fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
48        match decoder.read_byte()? {
49            0x00 => Ok(Limits {
50                min: decoder.decode()?,
51                max: None,
52            }),
53            0x01 => Ok(Limits {
54                min: decoder.decode()?,
55                max: Some(decoder.decode()?),
56            }),
57            _ => Err(DecodeError::new("invalid limits")),
58        }
59    }
60}