How can I assign a Pin to Option?

⚓ Rust    📅 2025-11-29    👤 surdeus    👁️ 4      

surdeus

I am unable to perform this. I believe the reason is that rustc thinks the Option<Pin> might be Some(exists_pin), which is why it refuses the overwrite, even though it is indeed None.

My other question is whether Pin::new_unchecked(&mut *mh) is unsound. I think it is safe, but Google AI insists it is unsound because the local reference will be dropped at the end of the function, and code like static N: i32 = 9; return &N; is a special case hard-coded into the compiler, making it sound, but only for that particular case.

pub fn mbuf_alloc_shared<T: Default>(mut nb: usize) -> Pin<&'static mut MyBuffer<T>> {
    let mut mbuf = MyBuffer::<T>::new();
    //   mbuf.mem_head is None

    nb += size_of::<MemHead<T>>();
    let layout = Layout::from_size_align(nb, align_of::<MemHead<T>>()).unwrap();
    let mem_head: Pin<&'static mut MemHead<T>> = unsafe {
        let mh = alloc(layout) as *mut MemHead<T>;
        ptr::write(ptr::addr_of_mut!((*mh).handle), -(nb as isize));
        ptr::write(
            ptr::addr_of_mut!((*mh).u),
            U {
                mem: ManuallyDrop::new((0, mem_head_addref_1::<T>)),
            },
        );
        ptr::write(ptr::addr_of_mut!((*mh).any), T::default());
        Pin::new_unchecked(&mut *mh)
    };
    mbuf.mem_head = Some(mem_head);

    todo!()
}

Edit: the first problem turned out mbuf is another Pin, my fault.

1 post - 1 participant

Read full topic

🏷️ Rust_feed