unchecked_mutable 0.1.0

Shared mutable without runtime cost
Documentation
//! 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 show_example<'a>() {
//!     let data = {
//!         let image: UncheckedMutable<Image> = UncheckedMutable::new(Image);
//!         image.data()
//!     };
//!
//!     let mut drawable: UncheckedMutable<Drawable> = UncheckedMutable::from_rc(data);
//!     let drawable: &mut (Drawable + 'a) = drawable.borrow_mut();
//!     drawable.draw();
//! }
//!
//! fn main() {
//!     show_example();
//! }
//! ```

#![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::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 }
    }

    /// 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)
    }
}