rust/crates/limit/src/lib.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

70 lines
1.7 KiB
Rust
Raw Normal View History

2021-07-10 15:49:17 -05:00
//! limit defines a struct to enforce limits.
#![warn(rust_2018_idioms, unused_lifetimes)]
2022-07-31 12:27:20 -05:00
#[cfg(feature = "tracking")]
use std::sync::atomic::AtomicUsize;
2021-07-10 15:49:17 -05:00
/// Represents a struct used to enforce a numerical limit.
#[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")]
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),
}
}
/// 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]
pub fn check(&self, other: usize) -> Result<(), ()> {
2021-07-10 15:49:17 -05:00
if other > self.upper_bound {
Err(())
} else {
#[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;
}
_ = self.max.compare_exchange_weak(
old_max,
other,
Ordering::Relaxed,
Ordering::Relaxed,
);
}
2021-07-10 15:49:17 -05:00
Ok(())
}
}
}