I\'m attempting to write Rust bindings for a C collection library (Judy Arrays [1]) which only provides itself room to store a pointer-width value. My company has a fair am
Instead of transmuting T
to usize
directly, you can transmute a &T
to &usize
:
pub fn insert(&mut self, val: T) {
unsafe {
let usize_ref: &usize = mem::transmute(&val);
self.v = *usize_ref;
}
}
Beware that this may read from an invalid memory location if the size of T
is smaller than the size of usize
or if the alignment requirements differ. This could cause a segfault. You can add an assertion to prevent this:
assert_eq!(mem::size_of::(), mem::size_of::());
assert!(mem::align_of::() <= mem::align_of::());