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

前端 未结 1 1542
既然无缘
既然无缘 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::(), mem::size_of::());
    assert!(mem::align_of::() <= mem::align_of::());
    

    0 讨论(0)
提交回复
热议问题