kernel::num

Module casts

Source
Expand description

Helpers for performing lossless integer casts.

The as keyword can be used to perform casts between integer types, but it unfortunately makes no distinction between casts that are lossless, and casts from a larger type into a smaller one that might silently strip data away. Thus, its use in the kernel is discouraged in favor of From implementations.

Conversely, there are casts that are lossless depending on the build architecture (such as casting usize to u64 on 32 or 64 bit archs), but not supported by From implementations in the standard library because they are not portable. It does however make sense for the kernel to support these, if only for code that is architecture-specific.

This module provides ways to perform such conversions safely:

  • A series of const functions (e.g. usize_as_u64) supporting safe conversions in const context. Conversions supported by From implementations in the standard library are also covered as the From trait cannot be used in const context.
  • Two extension traits, FromSafeCast and IntoSafeCast, providing conversion methods similar to From and Into for conversions that are safe to perform in the kernel, but not supported by the standard library.
  • Another series of const functions (e.g. u64_into_u8) supporting the conversion of a const value from a larger type into a smaller one, provided the value fits into the destination type. This is useful if a constant is defined as a larger type, but needs to be used as a smaller one.
  • An arch sub-module, defining more conversion functions that are only guaranteed to be lossless for a given pointer size. These can only be used in code that is specific to a given pointer size.

§Examples

use kernel::num::casts::{self, FromSafeCast, IntoSafeCast};

// Conversion from const context.
const USIZED_CONST: usize = casts::u8_as_usize(255u8);

// Non-const conversions.
let a = u64::from_safe_cast(4096usize);
let b: u64 = 4096usize.into_safe_cast();

Modules§

  • Conversions that are only lossless for the current architecture.

Traits§

Functions§