From 3dc2648f09ab2c27e22df1e0857bfea918f0c466 Mon Sep 17 00:00:00 2001 From: ClementTsang <34804052+ClementTsang@users.noreply.github.com> Date: Sun, 19 Nov 2023 01:48:51 -0500 Subject: [PATCH] other: add additional clamping functions on numeric types --- src/utils/gen_util.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/utils/gen_util.rs b/src/utils/gen_util.rs index ae35da8d2..42e24612b 100644 --- a/src/utils/gen_util.rs +++ b/src/utils/gen_util.rs @@ -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::*;