pub trait SaturatingAs {
    fn saturating_as<Dst>(self) -> Dst
    where
        Self: SaturatingCast<Dst>
; }
Expand description

Used to cast into the destination type, saturating if the value does not fit.

This is a convenience trait to enable writing src.saturating_as::<Dst>(). This would not work with the SaturatingCast::saturating_cast method because the SaturatingCast trait is generic while its SaturatingCast::saturating_cast method is not generic.

This trait’s method is suitable for chaining.

If there is an implementation of SaturatingCast<Dst> for &Src but not for Src, and the variable src is of type Src, then src.saturating_as::<Dst>() would not work and (&src).saturating_as::<Dst>() is not easy to use with chaining, but src.borrow().saturating_as::<Dst>() works.

Panics

This trait’s method panics if the value does not fit and saturation does not make sense, for example when trying to cast floating-point NaN into an integer type.

Examples

use az::SaturatingAs;
assert_eq!((-1).saturating_as::<u32>(), 0);
assert_eq!((17.0 + 256.0).saturating_as::<u8>(), 255);

The following example shows how this trait can be used when SaturatingCast is implemented for a reference type.

use az::{SaturatingAs, SaturatingCast};
use core::borrow::Borrow;
struct I(i32);
impl SaturatingCast<u32> for &'_ I {
    fn saturating_cast(self) -> u32 { self.0.saturating_cast() }
}

let r = &I(-5);
assert_eq!(r.saturating_as::<u32>(), 0);
let owned = I(12);
assert_eq!(owned.borrow().saturating_as::<u32>(), 12);

Required Methods

Casts the value.

Implementors