Trait CloneFromCell

unsafe trait CloneFromCell: Clone

Types for which cloning Cell<Self> is sound.

Safety

Implementing this trait for a type is sound if and only if the following code is sound for T = that type.

#![feature(cell_get_cloned)]
# use std::cell::{CloneFromCell, Cell};
fn clone_from_cell<T: CloneFromCell>(cell: &Cell<T>) -> T {
    unsafe { T::clone(&*cell.as_ptr()) }
}

Importantly, you can't just implement CloneFromCell for any arbitrary Copy type, e.g. the following is unsound:

#![feature(cell_get_cloned)]
# use std::cell::Cell;

#[derive(Copy, Debug)]
pub struct Bad<'a>(Option<&'a Cell<Bad<'a>>>, u8);

impl Clone for Bad<'_> {
    fn clone(&self) -> Self {
        let a: &u8 = &self.1;
        // when self.0 points to self, we write to self.1 while we have a live `&u8` pointing to
        // it -- this is UB
        self.0.unwrap().set(Self(None, 1));
        dbg!((a, self));
        Self(None, 0)
    }
}

// this is not sound
// unsafe impl CloneFromCell for Bad<'_> {}

Implementors