pub trait WrappingAs {
    fn wrapping_as<Dst>(self) -> Dst
    where
        Self: WrappingCast<Dst>
; }
Expand description

Wrapping cast.

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

This trait’s method is suitable for chaining.

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

Panics

This trait’s method panics if the value does not fit and cannot be wrapped, for example when trying to cast floating-point ∞ into an integer type.

Examples

use az::WrappingAs;
assert_eq!((-1).wrapping_as::<u32>(), u32::max_value());
assert_eq!((17.0 + 256.0).wrapping_as::<u8>(), 17);

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

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

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

Required methods

Casts the value.

Implementors