1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//! 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)
    }
}