cat_gateway/service/utilities/
convert.rspub(crate) fn from_saturating<
R: Copy + num_traits::identities::Zero + num_traits::Bounded,
T: Copy
+ TryInto<R>
+ std::ops::Sub<Output = T>
+ std::cmp::PartialOrd<T>
+ num_traits::identities::Zero,
>(
value: T,
) -> R {
match value.try_into() {
Ok(value) => value,
Err(_) => {
if value > T::zero() {
R::max_value()
} else {
R::min_value()
}
},
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[allow(clippy::float_cmp)]
fn from_saturating_tests() {
let x: u32 = from_saturating(0_u8);
assert!(x == 0);
let x: u32 = from_saturating(255_u8);
assert!(x == 255);
let x: i8 = from_saturating(0_u32);
assert!(x == 0);
let x: i8 = from_saturating(512_u32);
assert!(x == 127);
let x: i8 = from_saturating(-512_i32);
assert!(x == -128);
let x: u16 = from_saturating(-512_i32);
assert!(x == 0);
let x: f64 = from_saturating(0.0_f32);
assert!(x == 0.0);
let x: f64 = from_saturating(0_u32);
assert!(x == 0.0);
let x: f64 = from_saturating(65536_u32);
assert!(x == 65536.0_f64);
let x: f64 = from_saturating(i32::MIN);
assert!(x == -2_147_483_648.0_f64);
}
}