add util functors for is_zero/is_equal; move clamp to math utils

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk 2024-09-13 18:24:33 +00:00 committed by strawberry
parent bd75ff65c9
commit 63053640f1
3 changed files with 39 additions and 15 deletions

View file

@ -53,6 +53,38 @@ macro_rules! validated {
($($input:tt)+) => { $crate::expected!($($input)+) }
}
/// Functor for equality to zero
#[macro_export]
macro_rules! is_zero {
() => {
$crate::is_matching!(0)
};
}
/// Functor for equality i.e. .is_some_and(is_equal!(2))
#[macro_export]
macro_rules! is_equal_to {
($val:expr) => {
|x| (x == $val)
};
}
/// Functor for less i.e. .is_some_and(is_less_than!(2))
#[macro_export]
macro_rules! is_less_than {
($val:expr) => {
|x| (x < $val)
};
}
/// Functor for matches! i.e. .is_some_and(is_matching!('A'..='Z'))
#[macro_export]
macro_rules! is_matching {
($val:expr) => {
|x| matches!(x, $val)
};
}
/// Returns false if the exponential backoff has expired based on the inputs
#[inline]
#[must_use]
@ -118,3 +150,6 @@ fn try_into_err<Dst: TryFrom<Src>, Src>(e: <Dst as TryFrom<Src>>::Error) -> Erro
type_name::<Dst>()
))
}
#[inline]
pub fn clamp<T: Ord>(val: T, min: T, max: T) -> T { cmp::min(cmp::max(val, min), max) }

View file

@ -14,8 +14,6 @@ pub mod sys;
mod tests;
pub mod time;
use std::cmp;
pub use ::ctor::{ctor, dtor};
pub use algorithm::common_elements;
pub use bytes::{increment, u64_from_bytes, u64_from_u8, u64_from_u8x8};
@ -24,6 +22,7 @@ pub use debug::slice_truncated as debug_slice_truncated;
pub use hash::calculate_hash;
pub use html::Escape as HtmlEscape;
pub use json::{deserialize_from_str, to_canonical_object};
pub use math::clamp;
pub use mutex_map::{Guard as MutexMapGuard, MutexMap};
pub use rand::string as random_string;
pub use string::{str_from_bytes, string_from_bytes};
@ -31,14 +30,7 @@ pub use sys::available_parallelism;
pub use time::now_millis as millis_since_unix_epoch;
#[inline]
pub fn clamp<T: Ord>(val: T, min: T, max: T) -> T { cmp::min(cmp::max(val, min), max) }
#[inline]
pub fn exchange<T: Clone>(state: &mut T, source: T) -> T {
let ret = state.clone();
*state = source;
ret
}
pub fn exchange<T>(state: &mut T, source: T) -> T { std::mem::replace(state, source) }
#[must_use]
pub fn generate_keypair() -> Vec<u8> {

View file

@ -41,8 +41,5 @@ pub(crate) fn camel_to_snake_string(s: &str) -> String {
output
}
pub(crate) fn exchange<T: Clone>(state: &mut T, source: T) -> T {
let ret = state.clone();
*state = source;
ret
}
#[inline]
pub(crate) fn exchange<T>(state: &mut T, source: T) -> T { std::mem::replace(state, source) }