Trait bnum::cast::As

source ·
pub trait As {
    // Required method
    fn as_<T>(self) -> T
       where T: CastFrom<Self>,
             Self: Sized;
Expand description

Trait which allows panic-free casting between numeric types.

The behavior matches the behavior of the as conversion operator between primitive integers. This trait can be used to convert between bnum’s integer types, as well as between bnum’s integer types and Rust’s primitive integers. Conversions between Rust’s primitive integers themselves are also defined for consistency.

Required Methods§


fn as_<T>(self) -> T
where T: CastFrom<Self>, Self: Sized,

Casts self to type T. The semantics of numeric casting with the as operator are followed, so <T as As>::as_::<U> can be used in the same way as T as U for numeric conversions.

use bnum::types::{U256, I512, I256, U1024};
use bnum::cast::As;
// Cast `u64` to `U256`:
let a = 399872465243u64;
let b: U256 = a.as_();
assert_eq!(a.as_::<u16>(), b.as_());

// Cast `i128` to `I512`:
let c = -2098409234529234584094i128;
let d = c.as_::<I512>();
//assert_eq!(<I256>(), d.as_());

// Cast `I512` to `U1024` (result will be sign-extended with leading ones):
let e: U1024 = d.as_();
assert_eq!(d, e.as_());

// Cast `U256` to `f64` and back:
let f: f64 = b.as_();
assert_eq!(b, f.as_());



impl<U> As for U