Crate bytemuck

source ·
Expand description

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


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.


  • 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 documentation is always built with extern_crate_alloc cargo feature enabled.



  • allocationextern_crate_alloc
    Stuff to boost things in the alloc crate.
  • Checked versions of the casting functions exposed in crate root that support CheckedBitPattern types.


  • Find the offset in bytes of the given $field of $Type. Requires an already initialized $instance value to work with.


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



Derive Macros

  • Derive the AnyBitPattern trait for a struct
  • ByteEqderive
    Derive the PartialEq and Eq trait for a type
  • ByteHashderive
    Derive the Hash trait for a type
  • Derive the CheckedBitPattern trait for a struct or enum.
  • Derive the Contiguous trait for an enum
  • NoUninitderive
    Derive the NoUninit trait for a struct or enum
  • Podderive
    Derive the Pod trait for a struct
  • Derive the TransparentWrapper trait for a struct
  • Zeroablederive
    Derive the Zeroable trait for a struct