exarch_core/limit.rs
1//! Typed configuration limits.
2//!
3//! A limit is either a positive bound or no bound at all. [`Limit`] and
4//! [`RatioLimit`] make a zero limit or a non-positive ratio unrepresentable, so
5//! no later check has to reject one and no sentinel value (`u64::MAX`) has to
6//! stand for "unbounded".
7
8use std::num::NonZeroU64;
9use std::num::NonZeroUsize;
10
11use crate::ArchiveError;
12use crate::ConfigProblem;
13use crate::ConfigSetting;
14use crate::Result;
15
16/// Builds a [`NonZero`](std::num::NonZero) value from a constant, failing the
17/// build when the constant is zero.
18///
19/// # Examples
20///
21/// ```
22/// use std::num::NonZeroU64;
23///
24/// let limit: NonZeroU64 = exarch_core::non_zero!(1024);
25/// assert_eq!(limit.get(), 1024);
26/// ```
27///
28/// A zero constant does not compile:
29///
30/// ```compile_fail
31/// let _: std::num::NonZeroU64 = exarch_core::non_zero!(0);
32/// ```
33#[macro_export]
34macro_rules! non_zero {
35 ($value:expr) => {
36 const {
37 match ::std::num::NonZero::new($value) {
38 ::std::option::Option::Some(value) => value,
39 ::std::option::Option::None => panic!("non_zero! needs a non-zero value"),
40 }
41 }
42 };
43}
44
45/// Builds a [`RatioLimit`] from a constant, failing the build when it is not
46/// finite and positive.
47///
48/// # Examples
49///
50/// ```
51/// let ratio = exarch_core::ratio_limit!(50.0);
52/// assert_eq!(ratio.get(), 50.0);
53/// ```
54///
55/// A non-positive constant does not compile:
56///
57/// ```compile_fail
58/// let _ = exarch_core::ratio_limit!(0.0);
59/// ```
60#[macro_export]
61macro_rules! ratio_limit {
62 ($value:expr) => {
63 const {
64 match $crate::RatioLimit::new($value) {
65 ::std::option::Option::Some(ratio) => ratio,
66 ::std::option::Option::None => {
67 panic!("ratio_limit! needs a finite, positive value")
68 }
69 }
70 }
71 };
72}
73
74/// A positive bound, or no bound.
75///
76/// # Examples
77///
78/// ```
79/// use exarch_core::Limit;
80/// use exarch_core::non_zero;
81/// use std::num::NonZeroU64;
82///
83/// let bounded: Limit<NonZeroU64> = non_zero!(10).into();
84/// assert!(bounded.admits(10));
85/// assert!(!bounded.admits(11));
86/// assert!(Limit::<NonZeroU64>::Unbounded.admits(u64::MAX));
87/// ```
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89pub enum Limit<T> {
90 /// At most this many.
91 Bounded(T),
92 /// No bound.
93 Unbounded,
94}
95
96const _: () = assert!(size_of::<Limit<NonZeroU64>>() == size_of::<u64>());
97
98impl<T> From<T> for Limit<T> {
99 fn from(bound: T) -> Self {
100 Self::Bounded(bound)
101 }
102}
103
104impl Limit<NonZeroU64> {
105 /// Whether `value` is within the limit.
106 #[must_use]
107 pub const fn admits(self, value: u64) -> bool {
108 match self {
109 Self::Bounded(bound) => value <= bound.get(),
110 Self::Unbounded => true,
111 }
112 }
113
114 /// The bound as a number, `u64::MAX` when unbounded, for reporting.
115 #[must_use]
116 pub const fn ceiling(self) -> u64 {
117 match self {
118 Self::Bounded(bound) => bound.get(),
119 Self::Unbounded => u64::MAX,
120 }
121 }
122
123 /// Parses a runtime value, refusing zero.
124 ///
125 /// # Errors
126 ///
127 /// Returns [`ArchiveError::InvalidConfiguration`] naming `setting` when
128 /// `value` is zero.
129 pub fn parse(setting: ConfigSetting, value: u64) -> Result<Self> {
130 non_zero_u64(setting, value).map(Self::Bounded)
131 }
132}
133
134impl Limit<NonZeroUsize> {
135 /// Whether `value` is within the limit.
136 #[must_use]
137 pub const fn admits(self, value: usize) -> bool {
138 match self {
139 Self::Bounded(bound) => value <= bound.get(),
140 Self::Unbounded => true,
141 }
142 }
143
144 /// The bound as a number, `usize::MAX` when unbounded, for reporting.
145 #[must_use]
146 pub const fn ceiling(self) -> usize {
147 match self {
148 Self::Bounded(bound) => bound.get(),
149 Self::Unbounded => usize::MAX,
150 }
151 }
152
153 /// Parses a runtime value, refusing zero.
154 ///
155 /// # Errors
156 ///
157 /// Returns [`ArchiveError::InvalidConfiguration`] naming `setting` when
158 /// `value` is zero.
159 pub fn parse(setting: ConfigSetting, value: usize) -> Result<Self> {
160 non_zero_usize(setting, value).map(Self::Bounded)
161 }
162}
163
164/// Parses a runtime byte count, refusing zero.
165///
166/// # Errors
167///
168/// Returns [`ArchiveError::InvalidConfiguration`] naming `setting` when `value`
169/// is zero.
170pub fn non_zero_u64(setting: ConfigSetting, value: u64) -> Result<NonZeroU64> {
171 NonZeroU64::new(value).ok_or(ArchiveError::InvalidConfiguration {
172 setting,
173 problem: ConfigProblem::Zero,
174 })
175}
176
177/// Parses a signed integer from a binding, refusing zero, negative values and
178/// values above `u64::MAX`.
179///
180/// # Errors
181///
182/// Returns [`ArchiveError::InvalidConfiguration`] naming `setting` with
183/// [`ConfigProblem::Negative`], [`ConfigProblem::Zero`] or
184/// [`ConfigProblem::TooLarge`].
185///
186/// # Examples
187///
188/// ```
189/// use exarch_core::ConfigSetting;
190/// use exarch_core::positive_from_i128;
191///
192/// assert_eq!(positive_from_i128(ConfigSetting::MaxBytes, 7)?.get(), 7);
193/// assert!(positive_from_i128(ConfigSetting::MaxBytes, -1).is_err());
194/// assert!(positive_from_i128(ConfigSetting::MaxBytes, 0).is_err());
195/// assert!(positive_from_i128(ConfigSetting::MaxBytes, i128::from(u64::MAX) + 1).is_err());
196/// # Ok::<(), exarch_core::ArchiveError>(())
197/// ```
198pub fn positive_from_i128(setting: ConfigSetting, value: i128) -> Result<NonZeroU64> {
199 let refuse = |problem| ArchiveError::InvalidConfiguration { setting, problem };
200 if value < 0 {
201 return Err(refuse(ConfigProblem::Negative));
202 }
203 let value =
204 u64::try_from(value).map_err(|_| refuse(ConfigProblem::TooLarge { max: u64::MAX }))?;
205 non_zero_u64(setting, value)
206}
207
208/// The largest whole number an `f64` holds exactly (2^53 - 1), which is also
209/// `Number.MAX_SAFE_INTEGER`.
210const MAX_EXACT_F64: u64 = (1 << 53) - 1;
211
212/// Parses a floating-point number from a binding (a JavaScript number) into a
213/// positive whole count of at most 2^53 - 1.
214///
215/// # Errors
216///
217/// Returns [`ArchiveError::InvalidConfiguration`] naming `setting` with
218/// [`ConfigProblem::NotFinite`], [`ConfigProblem::Negative`],
219/// [`ConfigProblem::Zero`], [`ConfigProblem::NotWholeNumber`] or
220/// [`ConfigProblem::TooLarge`].
221///
222/// # Examples
223///
224/// ```
225/// use exarch_core::ConfigSetting;
226/// use exarch_core::positive_from_f64;
227///
228/// assert_eq!(positive_from_f64(ConfigSetting::MaxBytes, 12.0)?.get(), 12);
229/// for bad in [
230/// f64::NAN,
231/// f64::INFINITY,
232/// -1.0,
233/// 0.0,
234/// 1.5,
235/// 9_007_199_254_740_992.0,
236/// ] {
237/// assert!(positive_from_f64(ConfigSetting::MaxBytes, bad).is_err());
238/// }
239/// # Ok::<(), exarch_core::ArchiveError>(())
240/// ```
241#[expect(
242 clippy::cast_possible_truncation,
243 clippy::cast_sign_loss,
244 reason = "value is a whole number in 1..=2^53-1 after the checks"
245)]
246pub fn positive_from_f64(setting: ConfigSetting, value: f64) -> Result<NonZeroU64> {
247 let refuse = |problem| ArchiveError::InvalidConfiguration { setting, problem };
248 if !value.is_finite() {
249 return Err(refuse(ConfigProblem::NotFinite));
250 }
251 if value < 0.0 {
252 return Err(refuse(ConfigProblem::Negative));
253 }
254 if value == 0.0 {
255 return Err(refuse(ConfigProblem::Zero));
256 }
257 if value.fract() != 0.0 {
258 return Err(refuse(ConfigProblem::NotWholeNumber));
259 }
260 if value > MAX_EXACT_F64 as f64 {
261 return Err(refuse(ConfigProblem::TooLarge { max: MAX_EXACT_F64 }));
262 }
263 non_zero_u64(setting, value as u64)
264}
265
266/// Parses a runtime count, refusing zero.
267///
268/// # Errors
269///
270/// Returns [`ArchiveError::InvalidConfiguration`] naming `setting` when `value`
271/// is zero.
272pub fn non_zero_usize(setting: ConfigSetting, value: usize) -> Result<NonZeroUsize> {
273 NonZeroUsize::new(value).ok_or(ArchiveError::InvalidConfiguration {
274 setting,
275 problem: ConfigProblem::Zero,
276 })
277}
278
279/// A compression ratio limit: finite and greater than zero.
280///
281/// # Examples
282///
283/// ```
284/// use exarch_core::ConfigSetting;
285/// use exarch_core::RatioLimit;
286///
287/// let ratio = RatioLimit::parse(ConfigSetting::MaxCompressionRatio, 50.0)?;
288/// assert_eq!(ratio.get(), 50.0);
289/// assert!(RatioLimit::parse(ConfigSetting::MaxCompressionRatio, 0.0).is_err());
290/// assert!(RatioLimit::parse(ConfigSetting::MaxCompressionRatio, f64::NAN).is_err());
291/// # Ok::<(), exarch_core::ArchiveError>(())
292/// ```
293#[derive(Debug, Clone, Copy, PartialEq)]
294pub struct RatioLimit(f64);
295
296impl RatioLimit {
297 /// Parses a runtime ratio.
298 ///
299 /// # Errors
300 ///
301 /// Returns [`ArchiveError::InvalidConfiguration`] naming `setting` when
302 /// `ratio` is not finite ([`ConfigProblem::NotFinite`]), is negative
303 /// ([`ConfigProblem::Negative`]) or is zero ([`ConfigProblem::Zero`]).
304 pub fn parse(setting: ConfigSetting, ratio: f64) -> Result<Self> {
305 let problem = if !ratio.is_finite() {
306 ConfigProblem::NotFinite
307 } else if ratio < 0.0 {
308 ConfigProblem::Negative
309 } else {
310 ConfigProblem::Zero
311 };
312 Self::new(ratio).ok_or(ArchiveError::InvalidConfiguration { setting, problem })
313 }
314
315 /// The ratio.
316 #[must_use]
317 pub const fn get(self) -> f64 {
318 self.0
319 }
320
321 /// A ratio from a constant: `None` unless `ratio` is finite and positive.
322 ///
323 /// # Examples
324 ///
325 /// ```
326 /// use exarch_core::RatioLimit;
327 ///
328 /// assert_eq!(RatioLimit::new(100.0).map(RatioLimit::get), Some(100.0));
329 /// assert!(RatioLimit::new(f64::NAN).is_none());
330 /// ```
331 #[must_use]
332 pub const fn new(ratio: f64) -> Option<Self> {
333 if ratio.is_finite() && ratio > 0.0 {
334 Some(Self(ratio))
335 } else {
336 None
337 }
338 }
339}
340
341#[cfg(test)]
342#[allow(clippy::unwrap_used)]
343mod tests {
344 use super::*;
345
346 #[test]
347 fn zero_is_refused_with_its_setting() {
348 let err = Limit::<NonZeroU64>::parse(ConfigSetting::MaxFileSize, 0).unwrap_err();
349 assert_eq!(
350 err.to_string(),
351 "invalid configuration: max_file_size must not be zero"
352 );
353 assert!(Limit::<NonZeroUsize>::parse(ConfigSetting::MaxFileCount, 0).is_err());
354 }
355
356 #[test]
357 fn limits_admit_up_to_the_bound() {
358 let limit = Limit::<NonZeroU64>::parse(ConfigSetting::MaxFileSize, 7).unwrap();
359 assert!(limit.admits(7));
360 assert!(!limit.admits(8));
361 }
362
363 #[test]
364 fn ratios_must_be_finite_and_positive() {
365 for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
366 assert!(RatioLimit::parse(ConfigSetting::MaxCompressionRatio, bad).is_err());
367 }
368 }
369}