A crate for traits that describe certain memory layout invariants of a given type along with derive macros for deriving these traits for custom types.
This crate currently contains the following traits:
FixedLayout: types that have a well-defined layout that can be relied onNoUninit: types that do not have any unintialized bytesByteComplete: types where any appropriately sized and aligned array of bytes is a valid representation of that typeZeroable: types where all zeros are a valid representation of the type in memoryFromBytes: types where any appropriately sized and aligned array of bytes can be viewed as the type.AsBytes: The type can reliably be turned into a slice of bytes
fn safe_transmute<From: AsBytes, To: FromBytes>(from: From) -> To {
let from = &std::mem::ManuallyDrop::new(from);
assert!(std::mem::size_of::<From>() == std::mem::size_of::<To>(), "Cannot transmute to smaller type");
assert!(std::mem::align_of::<From>() % std::mem::align_of::<To>() == 0, "Not aligned");
unsafe { std::mem::transmute_copy(from) }
}There are several other crates that implement the same functionality as mem-markers even in part or in full. Here is a quick comparison. If you do not find your favorite crate here, please file an issue!
typic-typicaims to allow for "fearless transmute".typicis built on low-level primitives that can be used to build traits that represent the same invariants asmem-markerstraits. Where the crate differs is thattypicuses type-level programming for its implementation. This means thattypiccan generally express more subtle invariants thanmem-markers, but its implementation is more complex.typicalso does more thanmem-markersby providing functionality around safe transmute.mem-markersis purposefully only marker traits and any actual implementation is left for other crates.zerocopy-zerocopyhas similar levels of functionality totypicbut takes an approach more akin tomem-markers. The main difference is thatmem-markersaims at only exposing marker traits (at a more fine grained level thanzerocopy). It would be possible to implementzerocopyin terms onmem-markers, exposing additional functionality on top ofmem-markersmarker traits.- bytemuck -
bytemuck, much likezerocopy, is a high level crate for exposing safe transmute functionality. Similarly,bytemuckcould be implemented in terms ofmem-markers. safe-transmute-safe-transmutecompares tomem-markersin much the same way asbytemuckandzerocopy.