Skip to content

Commit

Permalink
Don't box value in Fragile<T> (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
Nilstrieb committed Oct 18, 2022
1 parent 3d3601a commit 0a99af0
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions src/fragile.rs
Expand Up @@ -16,9 +16,9 @@ use std::mem::ManuallyDrop;
/// the destructor will panic. Alternatively you can use `Sticky<T>` which is
/// not going to panic but might temporarily leak the value.
pub struct Fragile<T> {
// ManuallyDrop is necessary because we need to move out of this `Box` without running the
// ManuallyDrop is necessary because we need to move out of here without running the
// Drop code in functions like `into_inner`.
value: ManuallyDrop<Box<T>>,
value: ManuallyDrop<T>,
thread_id: NonZeroUsize,
}

Expand All @@ -31,7 +31,7 @@ impl<T> Fragile<T> {
/// only the original thread can interact with the value.
pub fn new(value: T) -> Self {
Fragile {
value: ManuallyDrop::new(Box::new(value)),
value: ManuallyDrop::new(value),
thread_id: thread_id::get(),
}
}
Expand Down Expand Up @@ -63,7 +63,7 @@ impl<T> Fragile<T> {

// SAFETY: `this` is not accessed beyond this point, and because it's in a ManuallyDrop its
// destructor is not run.
*unsafe { ManuallyDrop::take(&mut this.value) }
unsafe { ManuallyDrop::take(&mut this.value) }
}

/// Consumes the `Fragile`, returning the wrapped value if successful.
Expand All @@ -87,7 +87,7 @@ impl<T> Fragile<T> {
/// For a non-panicking variant, use [`try_get`](#method.try_get`).
pub fn get(&self) -> &T {
self.assert_thread();
&**self.value
&*self.value
}

/// Mutably borrows the wrapped value.
Expand All @@ -98,15 +98,15 @@ impl<T> Fragile<T> {
/// For a non-panicking variant, use [`try_get_mut`](#method.try_get_mut`).
pub fn get_mut(&mut self) -> &mut T {
self.assert_thread();
&mut **self.value
&mut *self.value
}

/// Tries to immutably borrow the wrapped value.
///
/// Returns `None` if the calling thread is not the one that wrapped the value.
pub fn try_get(&self) -> Result<&T, InvalidThreadAccess> {
if thread_id::get() == self.thread_id {
Ok(&**self.value)
Ok(&*self.value)
} else {
Err(InvalidThreadAccess)
}
Expand All @@ -117,7 +117,7 @@ impl<T> Fragile<T> {
/// Returns `None` if the calling thread is not the one that wrapped the value.
pub fn try_get_mut(&mut self) -> Result<&mut T, InvalidThreadAccess> {
if thread_id::get() == self.thread_id {
Ok(&mut **self.value)
Ok(&mut *self.value)
} else {
Err(InvalidThreadAccess)
}
Expand Down

0 comments on commit 0a99af0

Please sign in to comment.