Gilnaa / memoffset

offsetof for Rust
MIT License
224 stars 29 forks source link

Alternative implementation #1

Closed kornelski closed 7 years ago

kornelski commented 7 years ago

Current implementation creates a dummy object. It's possible to get alignment with just pointer manipulation.

        let base = std::mem::align_of::<Foo>(); // First valid non-NULL pointer address
        let ptr = base as *const Foo;
        assert_eq!(0, (&(*ptr).field) as *const _ as usize - base);

I think &(*ptr) is valid and does not actually deference the object, because such construct is also allowed for non-movable values (where *obj causes an error, but &*obj is fine).

Gilnaa commented 7 years ago

Actually it was implement like this at one point, but appearantly it is somewhat of a UB:

https://users.rust-lang.org/t/is-this-pointer-dereference-inherently-unsafe/13428/2

kornelski commented 7 years ago

Note that version I'm proposing is substantially different, because it doesn't use NULL.

Gilnaa commented 7 years ago

But it's still a pointer to an un-allocated, unknown piece of memory. AFAICT null is not special that way.

kornelski commented 7 years ago

OK