Skip to main content

coqui_access/
limit.rs

1//! A bound a caller can set or lift.
2
3use core::fmt;
4
5use coqui_builder::Leaf;
6use coqui_builder::describe::LeafError;
7
8/// At most a count, or no bound at all.
9///
10/// Libraries here state their resource bounds (entries, rules, bytes) as `Limit`s with a
11/// default the caller can change or lift. As configuration it is a number, or `none` for no
12/// bound. A document's `null` is a key that is not given, so it reads the default, not "no
13/// bound".
14///
15/// ```
16/// use coqui_access::Limit;
17///
18/// assert!(Limit::at(2).allows(2) && !Limit::at(2).allows(3));
19/// assert!(Limit::UNBOUNDED.allows(usize::MAX));
20/// ```
21#[derive(Clone, Copy, PartialEq, Eq, Hash)]
22pub struct Limit(Option<u32>);
23
24/// The text of a limit is its count, or `none`; `Display` stays the human wording.
25impl Leaf for Limit {
26    const TYPE: &'static str = "Limit";
27
28    fn to_text(&self) -> String {
29        match self.0 {
30            Some(most) => most.to_string(),
31            None => "none".to_owned(),
32        }
33    }
34
35    fn from_text(text: &str) -> Result<Self, LeafError> {
36        if text == "none" {
37            return Ok(Self::UNBOUNDED);
38        }
39        text.parse().map(Self::at).map_err(|_| LeafError::Invalid {
40            type_name: Self::TYPE,
41        })
42    }
43}
44
45impl Limit {
46    /// No bound.
47    pub const UNBOUNDED: Self = Self(None);
48
49    /// At most `count`.
50    pub const fn at(count: u32) -> Self {
51        Self(Some(count))
52    }
53
54    /// The count, or `None` for no bound.
55    pub const fn get(self) -> Option<u32> {
56        self.0
57    }
58
59    /// Whether `count` is within the bound.
60    pub fn allows(self, count: usize) -> bool {
61        self.0
62            .is_none_or(|most| usize::try_from(most).is_ok_and(|most| count <= most))
63    }
64
65    /// The bound as a `usize`, `usize::MAX` when there is none: for an API that takes a
66    /// plain maximum.
67    pub fn or_max(self) -> usize {
68        self.0.map_or(usize::MAX, |most| {
69            usize::try_from(most).unwrap_or(usize::MAX)
70        })
71    }
72}
73
74impl From<u32> for Limit {
75    fn from(count: u32) -> Self {
76        Self::at(count)
77    }
78}
79
80impl From<Option<u32>> for Limit {
81    fn from(count: Option<u32>) -> Self {
82        Self(count)
83    }
84}
85
86impl fmt::Debug for Limit {
87    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
88        match self.0 {
89            Some(most) => write!(formatter, "Limit({most})"),
90            None => formatter.write_str("Limit(unbounded)"),
91        }
92    }
93}
94
95impl fmt::Display for Limit {
96    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
97        match self.0 {
98            Some(most) => write!(formatter, "at most {most}"),
99            None => formatter.write_str("unbounded"),
100        }
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use coqui_builder::{Describe, Partial};
107
108    use super::*;
109
110    #[derive(Debug, PartialEq, Describe)]
111    struct Bounded {
112        #[map(default = Limit::at(256))]
113        entries: Limit,
114    }
115
116    fn read(key: &str, text: &str) -> Limit {
117        let mut partial = Partial::<Bounded>::new();
118        partial.set(key, text).unwrap();
119        partial.build().unwrap().entries
120    }
121
122    #[test]
123    fn a_limit_defaults_reads_none_as_unbounded_and_a_count_as_itself() {
124        assert_eq!(
125            Partial::<Bounded>::new().build().unwrap().entries,
126            Limit::at(256)
127        );
128        assert_eq!(read("entries", "none"), Limit::UNBOUNDED);
129        assert_eq!(read("entries", "3"), Limit::at(3));
130        let mut partial = Partial::<Bounded>::new();
131        for text in ["null", "unbounded", "-1", "1.5", ""] {
132            assert!(partial.set("entries", text).is_err(), "{text}");
133        }
134        coqui_builder::describe::assert_round_trip(&[
135            Limit::UNBOUNDED,
136            Limit::at(0),
137            Limit::at(u32::MAX),
138        ]);
139        assert!(Limit::UNBOUNDED.allows(usize::MAX));
140        assert!(Limit::at(0).allows(0) && !Limit::at(0).allows(1));
141        assert_eq!(Limit::UNBOUNDED.or_max(), usize::MAX);
142        assert_eq!(Limit::at(7).or_max(), 7);
143        assert_eq!(Limit::from(Some(4)).get(), Some(4));
144    }
145}