Skip to content

Comments on, and hopefully an increase of CopyCell soundness #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 2, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions src/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::marker::PhantomData;
/// library, but always require that the internal type implements `Copy`
/// and implements `Copy` itself.
#[derive(PartialEq, Eq)]
#[repr(transparent)]
pub struct CopyCell<T> {
/// Internal value
value: T,
Expand All @@ -32,27 +33,22 @@ impl<T> CopyCell<T> {
}

impl<T: Copy> CopyCell<T> {
#[inline]
fn mut_ptr(&self) -> *mut T {
&self.value as *const T as *mut T
}

/// Returns a copy of the contained value.
#[inline]
pub fn get(&self) -> T {
unsafe {
*self.mut_ptr()
}
self.value
}

/// Returns a mutable reference to the underlying data.
///
/// This call borrows `CopyCell` mutably, which gives us a compile time
/// memory safety guarantee.
#[inline]
pub fn get_mut(&mut self) -> &mut T {
pub fn get_mut<'a>(&'a mut self) -> &'a mut T {
// We can just cast the pointer from `CopyCell<T>` to `T` because of
// #[repr(transparent)]
unsafe {
&mut *self.mut_ptr()
&mut *(self as *mut CopyCell<T> as *mut T)
}
}

Expand All @@ -64,7 +60,14 @@ impl<T: Copy> CopyCell<T> {
// Regular write produces abnormal behavior when running tests in
// `--release` mode. Reordering writes when the compiler assumes
// things are immutable is dangerous.
unsafe { write_volatile(self.mut_ptr(), value) };
//
// We can just cast the pointer from `CopyCell<T>` to `T` because of
// #[repr(transparent)]
//
// This behavior is copied over from the std implementation of
// the `UnsafeCell`, and it's the best we can do right now in terms
// of soundness till we get a stable `UnsafeCell` that implements `Copy`.
unsafe { write_volatile(self as *const CopyCell<T> as *const T as *mut T, value) };
}
}

Expand Down