Rc and internal mutability

Rc::get_mut_unchecked probably should require no other Rc and Weak pointers to the same value. It's possible to cause unsafety without violating "Any other Rc or Weak pointers to the same value must not be dereferenced for the duration of the returned borrow" requirement.

#![feature(get_mut_unchecked)]

use std::rc::Rc;

unsafe fn f<'a>(mut r: Rc<&'a str>, s: &'a str) {
    *Rc::get_mut_unchecked(&mut r) = s;
}

fn main() {
    let x = Rc::new("Hello, world!");
    {
        let s = String::from("Replaced");
        unsafe { f(Rc::clone(&x), &s) };
    }
    println!("{}", x);
}

Rc::into_raw probably should return a pointer without involving deref however (similarly to how Weak already does it in its as_raw method).

I don't think Rc should be modified to use UnsafeCell, as this changes variance, when the current variance is fine, and this is not necessary when Rc::into_raw could be changed instead.

1 Like