2021-07-10 15:49:17 -05:00
|
|
|
//! limit defines a struct to enforce limits.
|
|
|
|
|
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.
|
|
|
|
pub struct Limit {
|
|
|
|
upper_bound: usize,
|
2021-07-31 10:25:45 -05:00
|
|
|
#[allow(unused)]
|
|
|
|
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 {
|
2021-07-31 10:25:45 -05:00
|
|
|
Self { upper_bound, max: AtomicUsize::new(0) }
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates a new limit.
|
|
|
|
#[inline]
|
|
|
|
#[cfg(feature = "tracking")]
|
|
|
|
pub const fn new_tracking(upper_bound: usize) -> Self {
|
|
|
|
Self { upper_bound, 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()
|
|
|
|
{
|
|
|
|
eprintln!("new max: {}", other);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-10 15:49:17 -05:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|