#struct #slice #memory #byte #tiny #instance #backs

as-bytes

Get the memory underlying a struct

2 unstable releases

0.2.0 Aug 31, 2021
0.1.0 Aug 28, 2021

#170 in #instance

Download history 6/week @ 2024-07-20 22/week @ 2024-07-27 3/week @ 2024-08-03 1/week @ 2024-08-17 15/week @ 2024-09-21 41/week @ 2024-09-28 17/week @ 2024-10-05 17/week @ 2024-10-12 7/week @ 2024-10-19 90/week @ 2024-10-26 4/week @ 2024-11-02

120 downloads per month

MIT license

6KB
71 lines

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
    ]
);

No runtime deps