Crates.io | as-bytes |
lib.rs | as-bytes |
version | 0.2.0 |
source | src |
created_at | 2021-08-28 03:46:21.533887 |
updated_at | 2021-08-31 18:58:17.563484 |
description | Get the memory underlying a struct |
homepage | |
repository | https://github.com/aatifsyed/as-bytes |
max_upload_size | |
id | 443323 |
size | 5,972 |
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
]
);