Trait sp_arithmetic::traits::SaturatedConversion
source · pub trait SaturatedConversion {
fn saturated_from<T>(t: T) -> Self
where
Self: UniqueSaturatedFrom<T>,
{ ... }
fn saturated_into<T>(self) -> T
where
Self: UniqueSaturatedInto<T>,
{ ... }
}Expand description
Convenience type to work around the highly unergonomic syntax needed
to invoke the functions of overloaded generic traits, in this case
SaturatedFrom and SaturatedInto.
Provided Methods§
sourcefn saturated_from<T>(t: T) -> Selfwhere
Self: UniqueSaturatedFrom<T>,
fn saturated_from<T>(t: T) -> Selfwhere
Self: UniqueSaturatedFrom<T>,
Convert from a value of T into an equivalent instance of Self.
This just uses UniqueSaturatedFrom internally but with this
variant you can provide the destination type using turbofish syntax
in case Rust happens not to assume the correct type.
sourcefn saturated_into<T>(self) -> Twhere
Self: UniqueSaturatedInto<T>,
fn saturated_into<T>(self) -> Twhere
Self: UniqueSaturatedInto<T>,
Consume self to return an equivalent value of T.
This just uses UniqueSaturatedInto internally but with this
variant you can provide the destination type using turbofish syntax
in case Rust happens not to assume the correct type.
Examples found in repository?
More examples
src/per_things.rs (line 511)
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
fn rational_mul_correction<N, P>(x: N, numer: P::Inner, denom: P::Inner, rounding: Rounding) -> N
where
N: MultiplyArg + UniqueSaturatedInto<P::Inner>,
P: PerThing,
P::Inner: Into<N>,
{
let numer_upper = P::Upper::from(numer);
let denom_n: N = denom.into();
let denom_upper = P::Upper::from(denom);
let rem = x.rem(denom_n);
// `rem` is less than `denom`, which fits in `P::Inner`.
let rem_inner = rem.saturated_into::<P::Inner>();
// `P::Upper` always fits `P::Inner::max_value().pow(2)`, thus it fits `rem * numer`.
let rem_mul_upper = P::Upper::from(rem_inner) * numer_upper;
// `rem` is less than `denom`, so `rem * numer / denom` is less than `numer`, which fits in
// `P::Inner`.
let mut rem_mul_div_inner = (rem_mul_upper / denom_upper).saturated_into::<P::Inner>();
match rounding {
// Already rounded down
Rounding::Down => {},
// Round up if the fractional part of the result is non-zero.
Rounding::Up => {
if rem_mul_upper % denom_upper > 0.into() {
// `rem * numer / denom` is less than `numer`, so this will not overflow.
rem_mul_div_inner += 1.into();
}
},
Rounding::NearestPrefDown =>
if rem_mul_upper % denom_upper > denom_upper / 2.into() {
// `rem * numer / denom` is less than `numer`, so this will not overflow.
rem_mul_div_inner += 1.into();
},
Rounding::NearestPrefUp =>
if rem_mul_upper % denom_upper >= denom_upper / 2.into() + denom_upper % 2.into() {
// `rem * numer / denom` is less than `numer`, so this will not overflow.
rem_mul_div_inner += 1.into();
},
}
rem_mul_div_inner.into()
}