[][src]Crate bytemuck

This crate gives small utilities for casting between plain data types.

Basics

Data comes in five basic forms in Rust, so we have five basic casting functions:

Some casts will never fail (eg: cast::<u32, f32> always works), other casts might fail (eg: cast_ref::<[u8; 4], u32> will fail if the reference isn't already aligned to 4). Each casting function has a "try" version which will return a Result, and the "normal" version which will simply panic on invalid input.

Using Your Own Types

All the functions here are guarded by the Pod trait, which is a sub-trait of the Zeroable trait.

If you're very sure that your type is eligible, you can implement those traits for your type and then they'll have full casting support. However, these traits are unsafe, and you should carefully read the requirements before adding the them to your own types.

Features

  • This crate is core only by default, but if you're using Rust 1.36 or later you can enable the extern_crate_alloc cargo feature for some additional methods related to Box and Vec. Note that the docs.rs documentation is always built with extern_crate_alloc cargo feature enabled.

Re-exports

pub use allocation::*;

Modules

allocation

Stuff to boost things in the alloc crate.

Macros

offset_of

Find the offset in bytes of the given $field of $Type, using $instance as an already-initialized value to work with.

Enums

PodCastError

The things that can go wrong when casting between Pod data forms.

Traits

Contiguous

A trait indicating that:

Pod

Marker trait for "plain old data".

TransparentWrapper

A trait which indicates that a type is a repr(transparent) wrapper around the Wrapped value.

Zeroable

Trait for types that can be safely created with zeroed.

Functions

bytes_of

Re-interprets &T as &[u8].

bytes_of_mut

Re-interprets &mut T as &mut [u8].

cast

Cast T into U

cast_mut

Cast &mut T into &mut U.

cast_ref

Cast &T into &U.

cast_slice

Cast &[T] into &[U].

cast_slice_mut

Cast &mut [T] into &mut [U].

from_bytes

Re-interprets &[u8] as &T.

from_bytes_mut

Re-interprets &mut [u8] as &mut T.

pod_align_to

As align_to, but safe because of the Pod bound.

pod_align_to_mut

As align_to_mut, but safe because of the Pod bound.

try_cast

Try to cast T into U.

try_cast_mut

Try to convert a &mut T into &mut U.

try_cast_ref

Try to convert a &T into &U.

try_cast_slice

Try to convert &[T] into &[U] (possibly with a change in length).

try_cast_slice_mut

Try to convert &mut [T] into &mut [U] (possibly with a change in length).

try_from_bytes

Re-interprets &[u8] as &T.

try_from_bytes_mut

Re-interprets &mut [u8] as &mut T.