Trait CastFrom

Source
pub trait CastFrom<T>: Sized {
    // Required method
    fn cast_from(value: T) -> Self;
}
Expand description

Like From but also support safe casts from/to usize and isize.

FromTryFromas castCastFrom
No runtime check
usize <-> u641
No truncation
No change of sign

From<usize> is not implemented for u64 even on platforms where the pointer width is 64 bit or lower (all currently supported targets).

Thus the following code fails to compile:

let a = usize::MAX;
let b = u64::from(a);
// Error: the trait `From<usize>` is not implemented for `u64`

Instead you have to resort to using TryFrom and unwrap:

let a = usize::MAX;
let b = u64::try_from(a).unwrap();

or using a potentially truncating/signedness-changing numeric cast using as:

let a = usize::MAX;
let b = a as u64;

If you want to guarantee that there are no runtime panics and the value will not be truncated, you can instead use CastFrom or CastInto:

use platform_cast::{CastFrom, CastInto};

let a = usize::MAX;
let b = u64::cast_from(a);

// Alternatively:
let b: u64 = a.cast_into();

The casts available depends on the target platform. The following code will only compile if the target pointer width is 64 bit or more.

use platform_cast::CastFrom;

let a = u64::MAX;
let b = usize::cast_from(a);
// On 32-bit targets: error[E0277]: the trait bound `usize: CastFrom<u64>`
is not satisfied

  1. Assuming a target with a pointer width of 64. 

Required Methods§

Source

fn cast_from(value: T) -> Self

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl CastFrom<i8> for isize

Source§

impl CastFrom<i16> for isize

Source§

impl CastFrom<i32> for isize

Source§

impl CastFrom<i64> for isize

Source§

impl CastFrom<isize> for i64

Source§

impl CastFrom<isize> for i128

Source§

impl CastFrom<u8> for usize

Source§

impl CastFrom<u16> for usize

Source§

impl CastFrom<u32> for usize

Source§

impl CastFrom<u64> for usize

Source§

impl CastFrom<usize> for u64

Source§

impl CastFrom<usize> for u128

Source§

impl CastFrom<NonZero<i8>> for NonZeroIsize

Source§

impl CastFrom<NonZero<i16>> for NonZeroIsize

Source§

impl CastFrom<NonZero<i32>> for NonZeroIsize

Source§

impl CastFrom<NonZero<i64>> for NonZeroIsize

Source§

impl CastFrom<NonZero<isize>> for NonZeroI64

Source§

impl CastFrom<NonZero<isize>> for NonZeroI128

Source§

impl CastFrom<NonZero<u8>> for NonZeroUsize

Source§

impl CastFrom<NonZero<u16>> for NonZeroUsize

Source§

impl CastFrom<NonZero<u32>> for NonZeroUsize

Source§

impl CastFrom<NonZero<u64>> for NonZeroUsize

Source§

impl CastFrom<NonZero<usize>> for NonZeroU64

Source§

impl CastFrom<NonZero<usize>> for NonZeroU128

Implementors§