Skip to content

Commit

Permalink
other: add additional clamping functions on numeric types
Browse files Browse the repository at this point in the history
  • Loading branch information
ClementTsang committed Nov 19, 2023
1 parent 7c14aa2 commit 3dc2648
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/utils/gen_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,41 @@ macro_rules! multi_eq_ignore_ascii_case {
};
}

/// A trait for additional clamping functions on numeric types.
pub trait ClampExt {
/// Restrict a value by a lower bound.
fn clamp_lower(&self, lower_bound: Self) -> Self;

/// Restrict a value by an upper bound.
fn clamp_upper(&self, upper_bound: Self) -> Self;
}

macro_rules! clamp_num_impl {
( $($NumType:ty),+ $(,)? ) => {
$(
impl ClampExt for $NumType {
fn clamp_lower(&self, lower_bound: Self) -> Self {
if *self < lower_bound {
lower_bound
} else {
*self
}
}

fn clamp_upper(&self, upper_bound: Self) -> Self {
if *self > upper_bound {
upper_bound
} else {
*self
}
}
}
)*
};
}

clamp_num_impl!(u8, u16, u32, u64, usize);

#[cfg(test)]
mod test {
use super::*;
Expand Down

0 comments on commit 3dc2648

Please sign in to comment.