Why does Rc<UnsafeCell<T>> remember its lifetime?


#1
//! Sometimes it is important to share something and avoid runtime costs.
//! This crate for such purpose
//! # Examples
//! ```
//! extern crate unchecked_mutable;
//!
//! use std::borrow::BorrowMut;
//! use unchecked_mutable::UncheckedMutable;
//!
//! trait Drawable {
//!     fn draw(&mut self);
//! }
//!
//! struct Image;
//!
//! impl Drawable for Image {
//!     fn draw(&mut self) {
//!         println!("Draw image");
//!     }
//! }
//!
//! fn main() {
//!     let data = {
//!         let image: UncheckedMutable<Image> = UncheckedMutable::new(Image);
//!         image.data()
//!     };
//!
//!     let mut drawable: UncheckedMutable<Drawable> = UncheckedMutable::from_rc(data);
//!     let drawable: &mut Drawable = drawable.borrow_mut();
//!     drawable.draw();
//! }
//! ```

#![feature(unsize)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]

use std::borrow::{Borrow, BorrowMut};
use std::cell::UnsafeCell;
use std::fmt::{Debug, Formatter, Error as FmtError};
use std::marker::{PhantomData, Unsize};
use std::rc::Rc;

/// It may be cloned as many times as needed.
/// It may be borrowed at once by multiple threads without any checks.
/// It is up to crate user to prevent any data races
pub struct UncheckedMutable<T: ?Sized> {
    data: Rc<UnsafeCell<T>>,
}

impl<T> UncheckedMutable<T> {
    /// Creates an instance from data
    pub fn new(data: T) -> Self {
        UncheckedMutable::from_rc(Rc::new(UnsafeCell::new(data)))
    }
}

impl<T: ?Sized> UncheckedMutable<T> {
    /// Creates an instance from already shared data.
    pub fn from_rc(data: Rc<UnsafeCell<T>>) -> Self {
        UncheckedMutable { data: data }
    }

    // /// Creates an instance from already shared data.
    // pub fn from_rc<U: ?Sized + Unsize<T>>(data: Rc<UnsafeCell<U>>) -> Self {
    //     UncheckedMutable {
    //         data: data as Rc<UnsafeCell<T>>,
    //         phantom_data: PhantomData::default(),
    //     }
    // }

    /// Returns owned data
    pub fn data(&self) -> Rc<UnsafeCell<T>> {
        self.data.clone()
    }
}

impl<T: ?Sized> Borrow<T> for UncheckedMutable<T> {
    fn borrow(&self) -> &T {
        unsafe { &*self.data.get() }
    }
}

impl<T: ?Sized> BorrowMut<T> for UncheckedMutable<T> {
    fn borrow_mut(&mut self) -> &mut T {
        unsafe { &mut *self.data.get() }
    }
}

impl<T: ?Sized> Clone for UncheckedMutable<T> {
    fn clone(&self) -> UncheckedMutable<T> {
        UncheckedMutable::from_rc(self.data.clone())
    }
}

impl<T: ?Sized + Debug> Debug for UncheckedMutable<T> {
    fn fmt(&self, formatter: &mut Formatter) -> Result<(), FmtError> {
        (self.borrow() as &T).fmt(formatter)
    }
}

trait Drawable {
    fn draw(&mut self);
}

struct Image;

impl Drawable for Image {
    fn draw(&mut self) {
        println!("Draw image");
    }
}

fn get_data() -> Rc<UnsafeCell<Drawable>> {
    let image: UncheckedMutable<Image> = UncheckedMutable::new(Image);
    image.data()
}

fn main() {
    let data = get_data();

    let mut drawable: UncheckedMutable<Drawable> = UncheckedMutable::from_rc(data);
    let drawable: &mut Drawable = drawable.borrow_mut();
    drawable.draw();
}

The compiler says

error: `drawable` does not live long enough
    let drawable: &mut Drawable = drawable.borrow_mut();
                                                 ^~~~~~~~
note: reference must be valid for the block suffix following statement 0 at 120:26...
        let data = get_data();
        let mut drawable: UncheckedMutable<Drawable> = UncheckedMutable::from_rc(data);
        let drawable: &mut Drawable = drawable.borrow_mut();
        drawable.draw();
    }
note: ...but borrowed value is only valid for the block suffix following statement 1 at 122:83
        let mut drawable: UncheckedMutable<Drawable> = UncheckedMutable::from_rc(data);
        let drawable: &mut Drawable = drawable.borrow_mut();
        drawable.draw();
    }

#2

That is weird. It appears to have something to do with the fact that an implementer of Drawable might contain borrowed data, but I can’t figure out why the compiler cares.

If the line

let drawable: &mut Drawable = drawable.borrow_mut();

is changed to

let drawable: &mut (Drawable + 'static) = drawable.borrow_mut();

then it compiles. Maybe someone with a better understanding of the borrow checker than I have can figure out why.


#3

This works

//! Sometimes it is important to share something and avoid runtime costs.
//! This crate for such purpose
//! # Examples
//! ```
//! extern crate unchecked_mutable;
//!
//! use std::borrow::BorrowMut;
//! use unchecked_mutable::UncheckedMutable;
//!
//! trait Drawable {
//!     fn draw(&mut self);
//! }
//!
//! struct Image;
//!
//! impl Drawable for Image {
//!     fn draw(&mut self) {
//!         println!("Draw image");
//!     }
//! }
//!
//! fn main() {
//!     let data = {
//!         let image: UncheckedMutable<Image> = UncheckedMutable::new(Image);
//!         image.data()
//!     };
//!
//!     let mut drawable: UncheckedMutable<Drawable> = UncheckedMutable::from_rc(data);
//!     let drawable: &mut Drawable = drawable.borrow_mut();
//!     drawable.draw();
//! }
//! ```

#![feature(unsize)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]

use std::borrow::{Borrow, BorrowMut};
use std::cell::UnsafeCell;
use std::fmt::{Debug, Formatter, Error as FmtError};
use std::marker::{PhantomData, Unsize};
use std::rc::Rc;

/// It may be cloned as many times as needed.
/// It may be borrowed at once by multiple threads without any checks.
/// It is up to crate user to prevent any data races
pub struct UncheckedMutable<T: ?Sized> {
    data: Rc<UnsafeCell<T>>,
}

impl<T> UncheckedMutable<T> {
    /// Creates an instance from data
    pub fn new(data: T) -> Self {
        UncheckedMutable::from_rc(Rc::new(UnsafeCell::new(data)))
    }
}

impl<T: ?Sized> UncheckedMutable<T> {
    /// Creates an instance from already shared data.
    pub fn from_rc(data: Rc<UnsafeCell<T>>) -> Self {
        UncheckedMutable { data: data }
    }

    // /// Creates an instance from already shared data.
    // pub fn from_rc<U: ?Sized + Unsize<T>>(data: Rc<UnsafeCell<U>>) -> Self {
    //     UncheckedMutable {
    //         data: data as Rc<UnsafeCell<T>>,
    //         phantom_data: PhantomData::default(),
    //     }
    // }

    /// Returns owned data
    pub fn data(&self) -> Rc<UnsafeCell<T>> {
        self.data.clone()
    }
}

impl<T: ?Sized> Borrow<T> for UncheckedMutable<T> {
    fn borrow(&self) -> &T {
        unsafe { &*self.data.get() }
    }
}

impl<T: ?Sized> BorrowMut<T> for UncheckedMutable<T> {
    fn borrow_mut(&mut self) -> &mut T {
        let data = self.data.get();
        unsafe { &mut *data }
    }
}

impl<T: ?Sized> Clone for UncheckedMutable<T> {
    fn clone(&self) -> Self {
        UncheckedMutable::from_rc(self.data.clone())
    }
}

impl<T: ?Sized + Debug> Debug for UncheckedMutable<T> {
    fn fmt(&self, formatter: &mut Formatter) -> Result<(), FmtError> {
        (self.borrow() as &T).fmt(formatter)
    }
}

trait Drawable {
    fn draw(&mut self);
}

struct Image;

impl Drawable for Image {
    fn draw(&mut self) {
        println!("Draw image");
    }
}

fn get_data() -> Rc<UnsafeCell<Drawable>> {
    let image: UncheckedMutable<Image> = UncheckedMutable::new(Image);
    image.data()
}

fn main<'a>() {
    let data = get_data();

    let mut drawable: UncheckedMutable<Drawable> = UncheckedMutable::from_rc(data);
    let drawable: &mut (Drawable + 'a) = drawable.borrow_mut();
    drawable.draw();
}