Pointer-stashing generics via `mem::transmute()`

前端 未结 1 1546
既然无缘
既然无缘 2021-01-18 22:57

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

相关标签:
1条回答
  • 2021-01-18 23:10

    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::<T>(), mem::size_of::<usize>());
    assert!(mem::align_of::<usize>() <= mem::align_of::<T>());
    
    0 讨论(0)
提交回复
热议问题