diff --git a/tokio-macros/src/entry.rs b/tokio-macros/src/entry.rs index 6a58b791ed8..eac4b230c76 100644 --- a/tokio-macros/src/entry.rs +++ b/tokio-macros/src/entry.rs @@ -65,7 +65,7 @@ fn parse_knobs( return Err(syn::Error::new_spanned( namevalue, "core_threads argument must be an int", - )) + )); } } } else { @@ -93,11 +93,14 @@ fn parse_knobs( return Err(syn::Error::new_spanned( namevalue, "max_threads argument must be an int", - )) + )); } }, name => { - let msg = format!("Unknown attribute pair {} is specified; expected one of: `core_threads`, `max_threads`", name); + let msg = format!( + "Unknown attribute pair {} is specified; expected one of: `core_threads`, `max_threads`", + name + ); return Err(syn::Error::new_spanned(namevalue, msg)); } } @@ -114,7 +117,10 @@ fn parse_knobs( } "basic_scheduler" => runtime = Some(runtime.unwrap_or_else(|| Runtime::Basic)), name => { - let msg = format!("Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", name); + let msg = format!( + "Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", + name + ); return Err(syn::Error::new_spanned(path, msg)); } } @@ -251,7 +257,10 @@ pub(crate) mod old { "threaded_scheduler" => runtime = Runtime::Threaded, "basic_scheduler" => runtime = Runtime::Basic, name => { - let msg = format!("Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", name); + let msg = format!( + "Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", + name + ); return syn::Error::new_spanned(path, msg).to_compile_error().into(); } } @@ -325,7 +334,10 @@ pub(crate) mod old { "threaded_scheduler" => runtime = Runtime::Threaded, "basic_scheduler" => runtime = Runtime::Basic, name => { - let msg = format!("Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", name); + let msg = format!( + "Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", + name + ); return syn::Error::new_spanned(path, msg).to_compile_error().into(); } } diff --git a/tokio/src/io/async_read.rs b/tokio/src/io/async_read.rs index cc9091c99c1..548f164ab37 100644 --- a/tokio/src/io/async_read.rs +++ b/tokio/src/io/async_read.rs @@ -124,7 +124,10 @@ pub trait AsyncRead { let b = &mut *(b as *mut [MaybeUninit] as *mut [u8]); let n = ready!(self.poll_read(cx, b))?; - assert!(n <= b.len(), "Bad AsyncRead implementation, more bytes were reported as read than the buffer can hold"); + assert!( + n <= b.len(), + "Bad AsyncRead implementation, more bytes were reported as read than the buffer can hold" + ); n }; diff --git a/tokio/src/loom/std/mod.rs b/tokio/src/loom/std/mod.rs index 60ee56ad202..c86308432d6 100644 --- a/tokio/src/loom/std/mod.rs +++ b/tokio/src/loom/std/mod.rs @@ -1,10 +1,10 @@ #![cfg_attr(any(not(feature = "full"), loom), allow(unused_imports, dead_code))] mod atomic_ptr; +mod atomic_u8; mod atomic_u16; mod atomic_u32; mod atomic_u64; -mod atomic_u8; mod atomic_usize; #[cfg(feature = "parking_lot")] mod parking_lot; @@ -61,10 +61,10 @@ pub(crate) mod sync { pub(crate) mod atomic { pub(crate) use crate::loom::std::atomic_ptr::AtomicPtr; + pub(crate) use crate::loom::std::atomic_u8::AtomicU8; pub(crate) use crate::loom::std::atomic_u16::AtomicU16; pub(crate) use crate::loom::std::atomic_u32::AtomicU32; pub(crate) use crate::loom::std::atomic_u64::AtomicU64; - pub(crate) use crate::loom::std::atomic_u8::AtomicU8; pub(crate) use crate::loom::std::atomic_usize::AtomicUsize; pub(crate) use std::sync::atomic::{spin_loop_hint, AtomicBool}; diff --git a/tokio/src/sync/mod.rs b/tokio/src/sync/mod.rs index e558634fd80..f217016eb3e 100644 --- a/tokio/src/sync/mod.rs +++ b/tokio/src/sync/mod.rs @@ -446,7 +446,7 @@ cfg_sync! { pub use semaphore::{Semaphore, SemaphorePermit, OwnedSemaphorePermit}; mod rwlock; - pub use rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard}; + pub use rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard, MappedRwLockReadGuard, MappedRwLockWriteGuard}; mod task; pub(crate) use task::AtomicWaker; diff --git a/tokio/src/sync/rwlock.rs b/tokio/src/sync/rwlock.rs index 4e2fb74d19e..ab51a18f938 100644 --- a/tokio/src/sync/rwlock.rs +++ b/tokio/src/sync/rwlock.rs @@ -1,5 +1,8 @@ -use crate::sync::batch_semaphore::{AcquireError, Semaphore}; +use crate::sync::batch_semaphore::Semaphore; use std::cell::UnsafeCell; +use std::fmt; +use std::marker; +use std::mem; use std::ops; #[cfg(not(loom))] @@ -76,6 +79,335 @@ pub struct RwLock { c: UnsafeCell, } +/// An RAII read lock guard returned by [`RwLockReadGuard::map`] or +/// [`MappedRwLockReadGuard::map`], which can point to a subfield of the +/// protected data. +/// +/// [`RwLockReadGuard::map`]: method@RwLockReadGuard::map +/// [`MappedRwLockReadGuard::map`]: method@MappedRwLockReadGuard::map +pub struct MappedRwLockReadGuard<'a, T> { + s: &'a Semaphore, + data: *const T, + marker: marker::PhantomData<&'a T>, +} + +impl<'a, T> MappedRwLockReadGuard<'a, T> { + /// Make a new `MappedRwLockReadGuard` for a component of the locked data. + /// + /// This operation cannot fail as the `MappedRwLockReadGuard` passed in + /// already locked the data. + /// + /// This is an associated function that needs to be + /// used as `MappedRwLockReadGuard::map(...)`. A method would interfere with + /// methods of the same name on the contents of the locked data. + /// + /// This is an asynchronous version of [`MappedRwLockReadGuard::map`] from the + /// [parking_lot crate]. + /// + /// [`MappedRwLockReadGuard::map`]: https://docs.rs/lock_api/latest/lock_api/struct.MappedRwLockReadGuard.html#method.map + /// [parking_lot crate]: https://crates.io/crates/parking_lot + /// + /// # Examples + /// + /// ``` + /// use tokio::sync::{RwLock, RwLockReadGuard, MappedRwLockReadGuard}; + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Bar(u32); + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Foo(Bar); + /// + /// # #[tokio::main] + /// # async fn main() { + /// let lock = RwLock::new(Foo(Bar(1))); + /// + /// let guard = lock.read().await; + /// let guard = RwLockReadGuard::map(guard, |f| &f.0); + /// let guard = MappedRwLockReadGuard::map(guard, |f| &f.0); + /// + /// assert_eq!(1, *guard); + /// # } + /// ``` + #[inline] + pub fn map(this: Self, f: F) -> MappedRwLockReadGuard<'a, U> + where + F: FnOnce(&T) -> &U, + { + let data = f(unsafe { &*this.data }); + let s = this.s; + // NB: Forget to avoid drop impl from being called. + mem::forget(this); + MappedRwLockReadGuard { + s, + data, + marker: marker::PhantomData, + } + } + + /// Attempts to make a new [`MappedRwLockReadGuard`] for a component of the + /// locked data. The original guard is returned if the closure returns + /// `None`. + /// + /// This operation cannot fail as the `MappedRwLockReadGuard` passed in + /// already locked the data. + /// + /// This is an associated function that needs to be used as + /// `MappedRwLockReadGuard::map(..)`. A method would interfere with methods + /// of the same name on the contents of the locked data. + /// + /// This is an asynchronous version of [`MappedRwLockReadGuard::try_map`] + /// from the [parking_lot crate]. + /// + /// [`MappedRwLockReadGuard::try_map`]: https://docs.rs/lock_api/latest/lock_api/struct.MappedRwLockReadGuard.html#method.try_map + /// [parking_lot crate]: https://crates.io/crates/parking_lot + /// + /// # Examples + /// + /// ``` + /// use tokio::sync::{RwLock, RwLockReadGuard, MappedRwLockReadGuard}; + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Bar(u32); + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Foo(Bar); + /// + /// # #[tokio::main] + /// # async fn main() { + /// let lock = RwLock::new(Foo(Bar(1))); + /// + /// let guard = lock.read().await; + /// let guard = RwLockReadGuard::try_map(guard, |f| Some(&f.0)).expect("should not fail"); + /// let guard = MappedRwLockReadGuard::try_map(guard, |f| Some(&f.0)).expect("should not fail"); + /// + /// assert_eq!(1, *guard); + /// # } + /// ``` + #[inline] + pub fn try_map(this: Self, f: F) -> Result, Self> + where + F: FnOnce(&T) -> Option<&U>, + { + let data = match f(unsafe { &*this.data }) { + Some(data) => data, + None => return Err(this), + }; + let s = this.s; + // NB: Forget to avoid drop impl from being called. + mem::forget(this); + Ok(MappedRwLockReadGuard { + s, + data, + marker: marker::PhantomData, + }) + } +} + +impl<'a, T> ops::Deref for MappedRwLockReadGuard<'a, T> { + type Target = T; + + #[inline] + fn deref(&self) -> &T { + unsafe { &*self.data } + } +} + +impl<'a, T> fmt::Debug for MappedRwLockReadGuard<'a, T> +where + T: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, T> fmt::Display for MappedRwLockReadGuard<'a, T> +where + T: fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +impl<'a, T> Drop for MappedRwLockReadGuard<'a, T> { + fn drop(&mut self) { + self.s.release(1); + } +} + +/// An RAII write lock guard returned by [`RwLockWriteGuard::map`] or +/// [`MappedRwLockWriteGuard::map`], which can point to a subfield of the +/// protected data. +/// +/// [`RwLockWriteGuard::map`]: method@RwLockWriteGuard::map +/// [`MappedRwLockWriteGuard::map`]: method@MappedRwLockWriteGuard::map +pub struct MappedRwLockWriteGuard<'a, T> { + s: &'a Semaphore, + data: *mut T, + marker: marker::PhantomData<&'a mut T>, +} + +impl<'a, T> MappedRwLockWriteGuard<'a, T> { + /// Make a new `MappedRwLockWriteGuard` for a component of the locked data. + /// + /// This operation cannot fail as the `MappedRwLockWriteGuard` passed in + /// already locked the data. + /// + /// This is an associated function that needs to be + /// used as `MappedRwLockWriteGuard::map(...)`. A method would interfere with + /// methods of the same name on the contents of the locked data. + /// + /// This is an asynchronous version of [`MappedRwLockWriteGuard::map`] from the + /// [parking_lot crate]. + /// + /// [`MappedRwLockWriteGuard::map`]: https://docs.rs/lock_api/latest/lock_api/struct.MappedRwLockWriteGuard.html#method.map + /// [parking_lot crate]: https://crates.io/crates/parking_lot + /// + /// # Examples + /// + /// ``` + /// use tokio::sync::{RwLock, RwLockWriteGuard, MappedRwLockWriteGuard}; + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Bar(u32); + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Foo(Bar); + /// + /// # #[tokio::main] + /// # async fn main() { + /// let lock = RwLock::new(Foo(Bar(1))); + /// + /// { + /// let guard = lock.write().await; + /// let guard = RwLockWriteGuard::map(guard, |f| &mut f.0); + /// let mut guard = MappedRwLockWriteGuard::map(guard, |f| &mut f.0); + /// *guard = 2; + /// } + /// + /// assert_eq!(Foo(Bar(2)), *lock.read().await); + /// # } + /// ``` + #[inline] + pub fn map(this: Self, f: F) -> MappedRwLockWriteGuard<'a, U> + where + F: FnOnce(&mut T) -> &mut U, + { + let data = f(unsafe { &mut *this.data }); + let s = this.s; + // NB: Forget to avoid drop impl from being called. + mem::forget(this); + MappedRwLockWriteGuard { + s, + data, + marker: marker::PhantomData, + } + } + + /// Attempts to make a new [`MappedRwLockWriteGuard`] for a component of the + /// locked data. The original guard is returned if the closure returns + /// `None`. + /// + /// This operation cannot fail as the `MappedRwLockWriteGuard` passed in + /// already locked the data. + /// + /// This is an associated function that needs to be used as + /// `MappedRwLockWriteGuard::map(..)`. A method would interfere with methods + /// of the same name on the contents of the locked data. + /// + /// This is an asynchronous version of [`MappedRwLockWriteGuard::try_map`] + /// from the [parking_lot crate]. + /// + /// [`MappedRwLockWriteGuard::try_map`]: https://docs.rs/lock_api/latest/lock_api/struct.MappedRwLockWriteGuard.html#method.try_map + /// [parking_lot crate]: https://crates.io/crates/parking_lot + /// + /// # Examples + /// + /// ``` + /// use tokio::sync::{RwLock, RwLockWriteGuard, MappedRwLockWriteGuard}; + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Bar(u32); + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Foo(Bar); + /// + /// # #[tokio::main] + /// # async fn main() { + /// let lock = RwLock::new(Foo(Bar(1))); + /// + /// { + /// let guard = lock.write().await; + /// let guard = RwLockWriteGuard::try_map(guard, |f| Some(&mut f.0)).expect("should not fail"); + /// let mut guard = MappedRwLockWriteGuard::try_map(guard, |f| Some(&mut f.0)).expect("should not fail"); + /// *guard = 2; + /// } + /// + /// assert_eq!(Foo(Bar(2)), *lock.read().await); + /// # } + /// ``` + #[inline] + pub fn try_map(this: Self, f: F) -> Result, Self> + where + F: FnOnce(&mut T) -> Option<&mut U>, + { + let data = match f(unsafe { &mut *this.data }) { + Some(data) => data, + None => return Err(this), + }; + let s = this.s; + // NB: Forget to avoid drop impl from being called. + mem::forget(this); + Ok(MappedRwLockWriteGuard { + s, + data, + marker: marker::PhantomData, + }) + } +} + +impl<'a, T> ops::Deref for MappedRwLockWriteGuard<'a, T> { + type Target = T; + + #[inline] + fn deref(&self) -> &T { + unsafe { &*self.data } + } +} + +impl<'a, T> ops::DerefMut for MappedRwLockWriteGuard<'a, T> { + #[inline] + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.data } + } +} + +impl<'a, T> fmt::Debug for MappedRwLockWriteGuard<'a, T> +where + T: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, T> fmt::Display for MappedRwLockWriteGuard<'a, T> +where + T: fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +impl<'a, T> Drop for MappedRwLockWriteGuard<'a, T> { + fn drop(&mut self) { + self.s.release(MAX_READS); + } +} + /// RAII structure used to release the shared read access of a lock when /// dropped. /// @@ -83,12 +415,140 @@ pub struct RwLock { /// [`RwLock`]. /// /// [`read`]: method@RwLock::read -#[derive(Debug)] +/// [`RwLock`]: struct@RwLock pub struct RwLockReadGuard<'a, T> { - permit: ReleasingPermit<'a, T>, lock: &'a RwLock, } +impl<'a, T> RwLockReadGuard<'a, T> { + /// Make a new `MappedRwLockReadGuard` for a component of the locked data. + /// + /// This operation cannot fail as the `RwLockReadGuard` passed in already + /// locked the data. + /// + /// This is an associated function that needs to be + /// used as `RwLockReadGuard::map(...)`. A method would interfere with + /// methods of the same name on the contents of the locked data. + /// + /// This is an asynchronous version of [`RwLockReadGuard::map`] from the + /// [parking_lot crate]. + /// + /// [`RwLockReadGuard::map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockReadGuard.html#method.map + /// [parking_lot crate]: https://crates.io/crates/parking_lot + /// + /// # Examples + /// + /// ``` + /// use tokio::sync::{RwLock, RwLockReadGuard}; + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Foo(u32); + /// + /// # #[tokio::main] + /// # async fn main() { + /// let lock = RwLock::new(Foo(1)); + /// + /// let guard = lock.read().await; + /// let guard = RwLockReadGuard::map(guard, |f| &f.0); + /// + /// assert_eq!(1, *guard); + /// # } + /// ``` + #[inline] + pub fn map(this: Self, f: F) -> MappedRwLockReadGuard<'a, U> + where + F: FnOnce(&T) -> &U, + { + let data = f(&*this) as *const U; + let s = &this.lock.s; + // NB: Forget to avoid drop impl from being called. + mem::forget(this); + MappedRwLockReadGuard { + s, + data, + marker: marker::PhantomData, + } + } + + /// Attempts to make a new [`MappedRwLockReadGuard`] for a component of the + /// locked data. The original guard is returned if the closure returns + /// `None`. + /// + /// This operation cannot fail as the `RwLockReadGuard` passed in already + /// locked the data. + /// + /// This is an associated function that needs to be used as + /// `RwLockReadGuard::try_map(..)`. A method would interfere with methods of the + /// same name on the contents of the locked data. + /// + /// This is an asynchronous version of [`RwLockReadGuard::try_map`] from the + /// [parking_lot crate]. + /// + /// [`RwLockReadGuard::try_map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockReadGuard.html#method.try_map + /// [parking_lot crate]: https://crates.io/crates/parking_lot + /// + /// # Examples + /// + /// ``` + /// use tokio::sync::{RwLock, RwLockReadGuard}; + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Foo(u32); + /// + /// # #[tokio::main] + /// # async fn main() { + /// let lock = RwLock::new(Foo(1)); + /// + /// let guard = lock.read().await; + /// let guard = RwLockReadGuard::try_map(guard, |f| Some(&f.0)).expect("should not fail"); + /// + /// assert_eq!(1, *guard); + /// # } + /// ``` + #[inline] + pub fn try_map(this: Self, f: F) -> Result, Self> + where + F: FnOnce(&T) -> Option<&U>, + { + let data = match f(&*this) { + Some(data) => data as *const U, + None => return Err(this), + }; + let s = &this.lock.s; + // NB: Forget to avoid drop impl from being called. + mem::forget(this); + Ok(MappedRwLockReadGuard { + s, + data, + marker: marker::PhantomData, + }) + } +} + +impl<'a, T> fmt::Debug for RwLockReadGuard<'a, T> +where + T: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, T> fmt::Display for RwLockReadGuard<'a, T> +where + T: fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +impl<'a, T> Drop for RwLockReadGuard<'a, T> { + fn drop(&mut self) { + self.lock.s.release(1); + } +} + /// RAII structure used to release the exclusive write access of a lock when /// dropped. /// @@ -97,32 +557,141 @@ pub struct RwLockReadGuard<'a, T> { /// /// [`write`]: method@RwLock::write /// [`RwLock`]: struct@RwLock -#[derive(Debug)] pub struct RwLockWriteGuard<'a, T> { - permit: ReleasingPermit<'a, T>, lock: &'a RwLock, } -// Wrapper arround Permit that releases on Drop -#[derive(Debug)] -struct ReleasingPermit<'a, T> { - num_permits: u16, - lock: &'a RwLock, +impl<'a, T> RwLockWriteGuard<'a, T> { + /// Make a new `MappedRwLockWriteGuard` for a component of the locked data. + /// + /// This operation cannot fail as the `RwLockWriteGuard` passed in already + /// locked the data. + /// + /// This is an associated function that needs to be used as + /// `RwLockWriteGuard::map(..)`. A method would interfere with methods of + /// the same name on the contents of the locked data. + /// + /// This is an asynchronous version of [`RwLockWriteGuard::map`] from the + /// [parking_lot crate]. + /// + /// [`RwLockWriteGuard::map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockWriteGuard.html#method.map + /// [parking_lot crate]: https://crates.io/crates/parking_lot + /// + /// # Examples + /// + /// ``` + /// use tokio::sync::{RwLock, RwLockWriteGuard}; + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Foo(u32); + /// + /// # #[tokio::main] + /// # async fn main() { + /// let lock = RwLock::new(Foo(1)); + /// + /// { + /// let mut mapped = RwLockWriteGuard::map(lock.write().await, |f| &mut f.0); + /// *mapped = 2; + /// } + /// + /// assert_eq!(Foo(2), *lock.read().await); + /// # } + /// ``` + #[inline] + pub fn map(mut this: Self, f: F) -> MappedRwLockWriteGuard<'a, U> + where + F: FnOnce(&mut T) -> &mut U, + { + let data = f(&mut *this) as *mut U; + let s = &this.lock.s; + // NB: Forget to avoid drop impl from being called. + mem::forget(this); + MappedRwLockWriteGuard { + s, + data, + marker: marker::PhantomData, + } + } + + /// Attempts to make a new [`MappedRwLockWriteGuard`] for a component of + /// the locked data. The original guard is returned if the closure returns + /// `None`. + /// + /// This operation cannot fail as the `RwLockWriteGuard` passed in already + /// locked the data. + /// + /// This is an associated function that needs to be + /// used as `RwLockWriteGuard::try_map(...)`. A method would interfere with + /// methods of the same name on the contents of the locked data. + /// + /// This is an asynchronous version of [`RwLockWriteGuard::try_map`] from + /// the [parking_lot crate]. + /// + /// [`RwLockWriteGuard::try_map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockWriteGuard.html#method.try_map + /// [parking_lot crate]: https://crates.io/crates/parking_lot + /// + /// # Examples + /// + /// ``` + /// use tokio::sync::{RwLock, RwLockWriteGuard}; + /// + /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] + /// struct Foo(u32); + /// + /// # #[tokio::main] + /// # async fn main() { + /// let lock = RwLock::new(Foo(1)); + /// + /// { + /// let guard = lock.write().await; + /// let mut guard = RwLockWriteGuard::try_map(guard, |f| Some(&mut f.0)).expect("should not fail"); + /// *guard = 2; + /// } + /// + /// assert_eq!(Foo(2), *lock.read().await); + /// # } + /// ``` + #[inline] + pub fn try_map(mut this: Self, f: F) -> Result, Self> + where + F: FnOnce(&mut T) -> Option<&mut U>, + { + let data = match f(&mut *this) { + Some(data) => data as *mut U, + None => return Err(this), + }; + let s = &this.lock.s; + // NB: Forget to avoid drop impl from being called. + mem::forget(this); + Ok(MappedRwLockWriteGuard { + s, + data, + marker: marker::PhantomData, + }) + } } -impl<'a, T> ReleasingPermit<'a, T> { - async fn acquire( - lock: &'a RwLock, - num_permits: u16, - ) -> Result, AcquireError> { - lock.s.acquire(num_permits).await?; - Ok(Self { num_permits, lock }) +impl<'a, T> fmt::Debug for RwLockWriteGuard<'a, T> +where + T: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) } } -impl<'a, T> Drop for ReleasingPermit<'a, T> { +impl<'a, T> fmt::Display for RwLockWriteGuard<'a, T> +where + T: fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +impl<'a, T> Drop for RwLockWriteGuard<'a, T> { fn drop(&mut self) { - self.lock.s.release(self.num_permits as usize); + self.lock.s.release(MAX_READS); } } @@ -139,12 +708,20 @@ fn bounds() { check_sync::>(); check_unpin::>(); + check_send::>(); check_sync::>(); check_unpin::>(); + check_send::>(); check_sync::>(); check_unpin::>(); + check_send::>(); + check_unpin::>(); + + check_send::>(); + check_unpin::>(); + let rwlock = RwLock::new(0); check_send_sync_val(rwlock.read()); check_send_sync_val(rwlock.write()); @@ -157,6 +734,15 @@ unsafe impl Send for RwLock where T: Send {} unsafe impl Sync for RwLock where T: Send + Sync {} unsafe impl<'a, T> Sync for RwLockReadGuard<'a, T> where T: Send + Sync {} unsafe impl<'a, T> Sync for RwLockWriteGuard<'a, T> where T: Send + Sync {} +// NB: These impls need to be explicit since we're storing a raw pointer. +// Safety: Stores a raw pointer to `T`, so if `T` is `Sync`, the lock guard over +// `T` is `Send`. +unsafe impl<'a, T> Send for MappedRwLockReadGuard<'a, T> where T: Sync {} +// Safety: Stores a raw pointer to `T`, so if `T` is `Sync`, the lock guard over +// `T` is `Send` - but since this is also provides mutable access, we need to +// make sure that `T` is `Send` since its value can be sent across thread +// boundaries. +unsafe impl<'a, T> Send for MappedRwLockWriteGuard<'a, T> where T: Send + Sync {} impl RwLock { /// Creates a new instance of an `RwLock` which is unlocked. @@ -207,12 +793,12 @@ impl RwLock { ///} /// ``` pub async fn read(&self) -> RwLockReadGuard<'_, T> { - let permit = ReleasingPermit::acquire(self, 1).await.unwrap_or_else(|_| { + self.s.acquire(1).await.unwrap_or_else(|_| { // The semaphore was closed. but, we never explicitly close it, and we have a // handle to it through the Arc, which means that this can never happen. unreachable!() }); - RwLockReadGuard { lock: self, permit } + RwLockReadGuard { lock: self } } /// Locks this rwlock with exclusive write access, causing the current task @@ -238,15 +824,15 @@ impl RwLock { ///} /// ``` pub async fn write(&self) -> RwLockWriteGuard<'_, T> { - let permit = ReleasingPermit::acquire(self, MAX_READS as u16) + self.s + .acquire(MAX_READS as u16) .await .unwrap_or_else(|_| { // The semaphore was closed. but, we never explicitly close it, and we have a // handle to it through the Arc, which means that this can never happen. unreachable!() }); - - RwLockWriteGuard { lock: self, permit } + RwLockWriteGuard { lock: self } } /// Consumes the lock, returning the underlying data. diff --git a/tokio/tests/fs_link.rs b/tokio/tests/fs_link.rs index cbbe27efe42..916f007f5a1 100644 --- a/tokio/tests/fs_link.rs +++ b/tokio/tests/fs_link.rs @@ -48,9 +48,11 @@ async fn test_symlink() { let src_2 = src.clone(); let dst_2 = dst.clone(); - assert!(fs::os::unix::symlink(src_2.clone(), dst_2.clone()) - .await - .is_ok()); + assert!( + fs::os::unix::symlink(src_2.clone(), dst_2.clone()) + .await + .is_ok() + ); let mut content = String::new();