as-bytes 0.2.0

Get the memory underlying a struct
Documentation
  • Coverage
  • 50%
    2 out of 4 items documented1 out of 4 items with examples
  • Size
  • Source code size: 5.59 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.08 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • aatifsyed/as-bytes
    1 1 1
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • aatifsyed

crates-io docs-rs github

as-bytes

A tiny crate, which provides slices to the memory which backs an instance of a struct.

use as_bytes::AsBytes;
let i = u32::MAX;
let bytes = unsafe { i.as_bytes() };
assert_eq!(bytes, [255, 255, 255, 255]);

You can use this to peek at structure layout. One usecase is for testing sending structs sent the wire. The below examples demonstrate two different packing attributes on the same structure.


let packed = ReprPacked {
    a: usize::MAX,
    b: 0u8,
    c: usize::MAX,
};
let bytes = unsafe { packed.as_bytes() };
assert_eq!(
    bytes,
    [255, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255]
);

let packed = ReprC {
    a: usize::MAX,
    b: 0u8,
    c: usize::MAX,
};
let bytes = unsafe { packed.as_bytes() };
assert_eq!(
    bytes,
    [
        255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255
    ]
);