pub trait PrimitiveNumberAs<T> { }Expand description
Trait for numeric conversions supported by the as keyword.
This is effectively the same as the type cast expression self as N, implemented for all
combinations of PrimitiveNumber.
§Examples
PrimitiveNumberAs<{number}> is a supertrait of PrimitiveNumber for all primitive floats
and integers, so you do not need to use this trait directly when converting concrete types.
use num_primitive::PrimitiveNumber;
// Clamp any number to the interval 0..=100, unless it is NaN.
fn clamp_percentage<Number: PrimitiveNumber>(x: Number) -> Number {
let clamped = x.as_to::<f64>().clamp(0.0, 100.0);
Number::as_from(clamped)
}
assert_eq!(clamp_percentage(-42_i8), 0_i8);
assert_eq!(clamp_percentage(42_u128), 42_u128);
assert_eq!(clamp_percentage(1e100_f64), 100_f64);
assert!(clamp_percentage(f32::NAN).is_nan());However, if the other type is also generic, an explicit type constraint is needed.
use num_primitive::{PrimitiveNumber, PrimitiveNumberAs};
fn clamp_any<Number, Limit>(x: Number, min: Limit, max: Limit) -> Number
where
Number: PrimitiveNumber + PrimitiveNumberAs<Limit>,
Limit: PartialOrd,
{
assert!(min <= max);
let y = x.as_to::<Limit>();
if y <= min {
Number::as_from(min)
} else if y >= max {
Number::as_from(max)
} else {
x
}
}
assert_eq!(clamp_any(1.23, 0_i8, 10_i8), 1.23);
assert_eq!(clamp_any(1.23, -1_i8, 1_i8), 1.0);
assert_eq!(clamp_any(i128::MAX, 0.0, 1e100), i128::MAX);Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.