Skip to main content

FromSafeCast

Trait FromSafeCast 

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

Extension trait providing guaranteed lossless cast to Self from T.

The standard library’s From implementations do not cover conversions that are not portable or future-proof. For instance, even though it is safe today, From<usize> is not implemented for u64 because of the possibility of needing to support larger-than-64bit architectures in the future.

The workaround is to either deal with the error handling of TryFrom for an operation that technically cannot fail, or to use the as keyword, which can silently strip data if the destination type is smaller than the source.

Both options are hardly acceptable for the kernel. It is also a much more architecture dependent environment, supporting only 32 and 64 bit architectures, with some modules explicitly depending on a specific bus width that could greatly benefit from infallible conversion operations.

Thus this extension trait that provides, for all architectures supported by the kernel, conversion methods between types for which such a cast is lossless.

In other words, this trait is implemented if, for all supported targets and with t: T, the t as Self operation is completely lossless.

Prefer this over the as keyword to guarantee that no lossy casts are performed.

If you need to perform a conversion in const context, use u32_as_usize, usize_as_u64, etc.

§Examples

use kernel::num::casts::FromSafeCast;

assert_eq!(usize::from_safe_cast(0xf00u32), 0xf00usize);

Required Methods§

Source

fn from_safe_cast(value: T) -> Self

Create a Self from value. This operation is guaranteed to be lossless.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl FromSafeCast<u32> for usize

Source§

fn from_safe_cast(value: u32) -> Self

Source§

impl FromSafeCast<usize> for u64

Source§

fn from_safe_cast(value: usize) -> Self

Implementors§