Moving ?Sized types on stable

⚓ Rust    📅 2025-08-08    👤 surdeus    👁️ 6      

surdeus

I'm working on a custom smart pointer. I've encountered a need for the unstable <*mut T>::with_metadata_of and I'm trying to figure out if there's any kind of workaround on stable. Essentially, I have a valid pointer to an object of T: ?Sized and I want to move it to a newly allocated location. E.g.

unsafe fn move_obj<T: ?Sized>(src: *const T, dst: *mut u8) -> *mut T {
    unsafe {
        let value_size = core::mem::size_of_val(&*src);
        core::ptr::copy_nonoverlapping(
            src as *const u8,
            dst,
            value_size,
        );
    }

    // copy the pointer metadata in case of a slice or trait object
    dst.with_metadata_of(src)
}

I've tried a few different (hacky) things, like src.with_addr(dst.expose_provenance()), but I end up with provenance errors in miri, which makes sense. It's just frustrating because I know that the pointer is correct modulo provenance, but there doesn't seem to be a way to move metadata without losing provenance.

I suspect this just isn't possible to accomplish on stable, but I wanted to check if anyone knows of any way to do it that I haven't considered before I give up on it.

1 post - 1 participant

Read full topic

🏷️ Rust_feed