Skip to content

Commit

Permalink
Use PhantomPinned in RWLock to enforce Pin usage.
Browse files Browse the repository at this point in the history
  • Loading branch information
m-ou-se committed Oct 21, 2020
1 parent 9b2112a commit 9b48a5f
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions library/std/src/sys_common/rwlock.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::marker::PhantomPinned;
use crate::pin::Pin;
use crate::sys::rwlock as imp;

Expand All @@ -6,22 +7,25 @@ use crate::sys::rwlock as imp;
/// This structure is entirely unsafe and serves as the lowest layer of a
/// cross-platform binding of system rwlocks. It is recommended to use the
/// safer types at the top level of this crate instead of this type.
pub struct RWLock(imp::RWLock);
pub struct RWLock {
inner: imp::RWLock,
_pinned: PhantomPinned,
}

impl RWLock {
/// Creates a new reader-writer lock for use.
///
/// Behavior is undefined if the reader-writer lock is moved after it is
/// first used with any of the functions below.
pub const fn new() -> RWLock {
RWLock(imp::RWLock::new())
RWLock { inner: imp::RWLock::new(), _pinned: PhantomPinned }
}

/// Acquires shared access to the underlying lock, blocking the current
/// thread to do so.
#[inline]
pub fn read(self: Pin<&Self>) {
unsafe { self.0.read() }
unsafe { self.inner.read() }
}

/// Attempts to acquire shared access to this lock, returning whether it
Expand All @@ -30,14 +34,14 @@ impl RWLock {
/// This function does not block the current thread.
#[inline]
pub fn try_read(self: Pin<&Self>) -> bool {
unsafe { self.0.try_read() }
unsafe { self.inner.try_read() }
}

/// Acquires write access to the underlying lock, blocking the current thread
/// to do so.
#[inline]
pub fn write(self: Pin<&Self>) {
unsafe { self.0.write() }
unsafe { self.inner.write() }
}

/// Attempts to acquire exclusive access to this lock, returning whether it
Expand All @@ -46,15 +50,15 @@ impl RWLock {
/// This function does not block the current thread.
#[inline]
pub fn try_write(self: Pin<&Self>) -> bool {
unsafe { self.0.try_write() }
unsafe { self.inner.try_write() }
}

/// Unlocks previously acquired shared access to this lock.
///
/// Behavior is undefined if the current thread does not have shared access.
#[inline]
pub unsafe fn read_unlock(self: Pin<&Self>) {
self.0.read_unlock()
self.inner.read_unlock()
}

/// Unlocks previously acquired exclusive access to this lock.
Expand All @@ -63,7 +67,7 @@ impl RWLock {
/// exclusive access.
#[inline]
pub unsafe fn write_unlock(self: Pin<&Self>) {
self.0.write_unlock()
self.inner.write_unlock()
}
}

Expand All @@ -72,6 +76,6 @@ impl Drop for RWLock {
fn drop(&mut self) {
// SAFETY: The rwlock wasn't moved since using any of its
// functions, because they all require a Pin.
unsafe { self.0.destroy() }
unsafe { self.inner.destroy() }
}
}

0 comments on commit 9b48a5f

Please sign in to comment.