Trait az::OverflowingAs

source ·
pub trait OverflowingAs {
    // Required method
    fn overflowing_as<Dst>(self) -> (Dst, bool)
       where Self: OverflowingCast<Dst>;
}
Expand description

Used for overflowing casts.

This trait’s method returns a [tuple] of the value and a [bool], indicating whether an overflow has occurred. On overflow, the wrapped value is returned.

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

This trait’s method is suitable for chaining.

If there is an implementation of OverflowingCast<Dst> for &Src but not for Src, and the variable src is of type Src, then src.overflowing_as::<Dst>() would not work and (&src).overflowing_as::<Dst>() is not easy to use with chaining, but src.borrow().overflowing_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::OverflowingAs;
assert_eq!(17i32.overflowing_as::<u8>(), (17, false));
assert_eq!((-1).overflowing_as::<u32>(), (u32::max_value(), true));
assert_eq!((17.0 + 256.0).overflowing_as::<u8>(), (17, true));

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

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

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

Required Methods§

source

fn overflowing_as<Dst>(self) -> (Dst, bool)
where Self: OverflowingCast<Dst>,

Casts the value.

Object Safety§

This trait is not object safe.

Implementors§

source§

impl<T> OverflowingAs for T