2021-07-10 15:49:17 -05:00
|
|
|
//! limit defines a struct to enforce limits.
|
|
|
|
|
2023-12-05 04:35:09 -06:00
|
|
|
#![warn(rust_2018_idioms, unused_lifetimes)]
|
2022-07-20 07:59:42 -05:00
|
|
|
|
2022-07-31 12:27:20 -05:00
|
|
|
#[cfg(feature = "tracking")]
|
2021-07-31 10:25:45 -05:00
|
|
|
use std::sync::atomic::AtomicUsize;
|
|
|
|
|
2021-07-10 15:49:17 -05:00
|
|
|
/// Represents a struct used to enforce a numerical limit.
|
2023-04-17 10:31:39 -05:00
|
|
|
#[derive(Debug)]
|
2021-07-10 15:49:17 -05:00
|
|
|
pub struct Limit {
|
|
|
|
upper_bound: usize,
|
2022-07-31 12:27:20 -05:00
|
|
|
#[cfg(feature = "tracking")]
|
2021-07-31 10:25:45 -05:00
|
|
|
max: AtomicUsize,
|
2021-07-10 15:49:17 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Limit {
|
|
|
|
/// Creates a new limit.
|
|
|
|
#[inline]
|
|
|
|
pub const fn new(upper_bound: usize) -> Self {
|
2022-07-31 12:27:20 -05:00
|
|
|
Self {
|
|
|
|
upper_bound,
|
|
|
|
#[cfg(feature = "tracking")]
|
|
|
|
max: AtomicUsize::new(0),
|
|
|
|
}
|
2021-07-31 10:25:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates a new limit.
|
|
|
|
#[inline]
|
|
|
|
#[cfg(feature = "tracking")]
|
|
|
|
pub const fn new_tracking(upper_bound: usize) -> Self {
|
2022-07-31 12:27:20 -05:00
|
|
|
Self {
|
|
|
|
upper_bound,
|
|
|
|
#[cfg(feature = "tracking")]
|
|
|
|
max: AtomicUsize::new(1),
|
|
|
|
}
|
2021-07-10 15:49:17 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Gets the underlying numeric limit.
|
|
|
|
#[inline]
|
|
|
|
pub const fn inner(&self) -> usize {
|
|
|
|
self.upper_bound
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Checks whether the given value is below the limit.
|
|
|
|
/// Returns `Ok` when `other` is below `self`, and `Err` otherwise.
|
|
|
|
#[inline]
|
2021-07-31 10:25:45 -05:00
|
|
|
pub fn check(&self, other: usize) -> Result<(), ()> {
|
2021-07-10 15:49:17 -05:00
|
|
|
if other > self.upper_bound {
|
|
|
|
Err(())
|
|
|
|
} else {
|
2021-07-31 10:25:45 -05:00
|
|
|
#[cfg(feature = "tracking")]
|
|
|
|
loop {
|
|
|
|
use std::sync::atomic::Ordering;
|
|
|
|
let old_max = self.max.load(Ordering::Relaxed);
|
|
|
|
if other <= old_max || old_max == 0 {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
if self
|
|
|
|
.max
|
2022-01-28 09:19:35 -06:00
|
|
|
.compare_exchange_weak(old_max, other, Ordering::Relaxed, Ordering::Relaxed)
|
2021-07-31 10:25:45 -05:00
|
|
|
.is_ok()
|
|
|
|
{
|
2022-12-23 12:42:58 -06:00
|
|
|
eprintln!("new max: {other}");
|
2021-07-31 10:25:45 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-10 15:49:17 -05:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|