zerocopy

The zerocopy crate (from Fuchsia) provides traits and macros for safely converting between byte sequences and other types.

  1. use zerocopy::{Immutable, IntoBytes};
  2. #[repr(u32)]
  3. #[derive(Debug, Default, Immutable, IntoBytes)]
  4. enum RequestType {
  5.     #[default]
  6.     In = 0,
  7.     Out = 1,
  8.     Flush = 4,
  9. }
  10. #[repr(C)]
  11. #[derive(Debug, Default, Immutable, IntoBytes)]
  12. struct VirtioBlockRequest {
  13.     request_type: RequestType,
  14.     reserved: u32,
  15.     sector: u64,
  16. }
  17. fn main() {
  18.     let request = VirtioBlockRequest {
  19.         request_type: RequestType::Flush,
  20.         sector: 42,
  21.         ..Default::default()
  22.     };
  23.     assert_eq!(
  24.         request.as_bytes(),
  25.         &[4, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 0, 0, 0, 0]
  26.     );
  27. }

This is not suitable for MMIO (as it doesn’t use volatile reads and writes), but can be useful for working with structures shared with hardware e.g. by DMA, or sent over some external interface.

  • FromBytes can be implemented for types for which any byte pattern is valid, and so can safely be converted from an untrusted sequence of bytes.
  • Attempting to derive FromBytes for these types would fail, because RequestType doesn’t use all possible u32 values as discriminants, so not all byte patterns are valid.
  • zerocopy::byteorder has types for byte-order aware numeric primitives.
  • Run the example with cargo run under src/bare-metal/useful-crates/zerocopy-example/. (It won’t run in the Playground because of the crate dependency.)