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