Restructure std::sync wrappers

This commit is contained in:
2022-07-04 21:25:46 +02:00
parent 764d3df454
commit 6e5516eaa7
2 changed files with 526 additions and 577 deletions

View File

@@ -41,7 +41,7 @@
//! //!
//! These operations have been reasonably optimized, but the performance penalty may yet be too much //! These operations have been reasonably optimized, but the performance penalty may yet be too much
//! for production use. In those cases, it may be beneficial to instead use debug-only versions //! for production use. In those cases, it may be beneficial to instead use debug-only versions
//! (such as [`stdsync::DebugMutex`]) which evaluate to a tracing mutex when debug assertions are //! (such as [`stdsync::Mutex`]) which evaluate to a tracing mutex when debug assertions are
//! enabled, and to the underlying mutex when they're not. //! enabled, and to the underlying mutex when they're not.
//! //!
//! [paper]: https://whileydave.com/publications/pk07_jea/ //! [paper]: https://whileydave.com/publications/pk07_jea/

View File

@@ -1,130 +1,83 @@
//! Tracing mutex wrappers for locks found in `std::sync`. //! Tracing mutex wrappers for locks found in `std::sync`.
//! //!
//! This module provides wrappers for `std::sync` primitives with exactly the same API and //! This module provides wrappers for `std::sync` primitives with exactly the same API and
//! functionality as their counterparts, with the exception that their acquisition order is //! functionality as their counterparts, with the exception that their acquisition order is tracked.
//! tracked. //!
//! Dedicated wrappers that provide the dependency tracing can be found in the [`tracing`] module.
//! The original primitives are available from [`std::sync`], imported as [`raw`] for convenience.
//!
//! If debug assertions are enabled, this module imports the primitives from [`tracing`], otherwise
//! it will import from [`raw`].
//! //!
//! ```rust //! ```rust
//! # use tracing_mutex::stdsync::TracingMutex; //! # use tracing_mutex::stdsync::tracing::Mutex;
//! # use tracing_mutex::stdsync::TracingRwLock; //! # use tracing_mutex::stdsync::tracing::RwLock;
//! let mutex = TracingMutex::new(()); //! let mutex = Mutex::new(());
//! mutex.lock().unwrap(); //! mutex.lock().unwrap();
//! //!
//! let rwlock = TracingRwLock::new(()); //! let rwlock = RwLock::new(());
//! rwlock.read().unwrap(); //! rwlock.read().unwrap();
//! ``` //! ```
use std::fmt; pub use std::sync as raw;
use std::ops::Deref;
use std::ops::DerefMut;
use std::sync::Condvar;
use std::sync::LockResult;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::Once;
use std::sync::OnceState;
use std::sync::PoisonError;
use std::sync::RwLock;
use std::sync::RwLockReadGuard;
use std::sync::RwLockWriteGuard;
use std::sync::TryLockError;
use std::sync::TryLockResult;
use std::sync::WaitTimeoutResult;
use std::time::Duration;
use crate::BorrowedMutex;
use crate::LazyMutexId;
use crate::MutexId;
/// Debug-only tracing `Mutex`.
///
/// Type alias that resolves to [`TracingMutex`] when debug assertions are enabled and to
/// [`std::sync::Mutex`] when they're not. Use this if you want to have the benefits of cycle
/// detection in development but do not want to pay the performance penalty in release.
#[cfg(debug_assertions)]
pub type DebugMutex<T> = TracingMutex<T>;
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
pub type DebugMutex<T> = Mutex<T>; pub use std::sync::{Condvar, Mutex, MutexGuard, Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
/// Mutex guard for [`DebugMutex`].
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
pub type DebugMutexGuard<'a, T> = TracingMutexGuard<'a, T>; pub use tracing::{Condvar, Mutex, MutexGuard, Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
#[cfg(not(debug_assertions))]
pub type DebugMutexGuard<'a, T> = MutexGuard<'a, T>;
/// Debug-only `Condvar` /// Dependency tracing versions of [`std::sync`].
/// pub mod tracing {
/// Type alias that accepts the mutex guard emitted from [`DebugMutex`]. use std::fmt;
#[cfg(debug_assertions)] use std::ops::Deref;
pub type DebugCondvar = TracingCondvar; use std::ops::DerefMut;
#[cfg(not(debug_assertions))] use std::sync;
pub type DebugCondvar = Condvar; use std::sync::LockResult;
use std::sync::OnceState;
use std::sync::PoisonError;
use std::sync::TryLockError;
use std::sync::TryLockResult;
use std::sync::WaitTimeoutResult;
use std::time::Duration;
/// Debug-only tracing `RwLock`. use crate::BorrowedMutex;
/// use crate::LazyMutexId;
/// Type alias that resolves to [`TracingRwLock`] when debug assertions are enabled and to use crate::MutexId;
/// [`std::sync::RwLock`] when they're not. Use this if you want to have the benefits of cycle
/// detection in development but do not want to pay the performance penalty in release.
#[cfg(debug_assertions)]
pub type DebugRwLock<T> = TracingRwLock<T>;
#[cfg(not(debug_assertions))]
pub type DebugRwLock<T> = RwLock<T>;
/// Read guard for [`DebugRwLock`]. /// Wrapper for [`std::sync::Mutex`].
#[cfg(debug_assertions)] ///
pub type DebugReadGuard<'a, T> = TracingReadGuard<'a, T>; /// Refer to the [crate-level][`crate`] documentation for the differences between this struct and
#[cfg(not(debug_assertions))] /// the one it wraps.
pub type DebugReadGuard<'a, T> = RwLockReadGuard<'a, T>; #[derive(Debug, Default)]
pub struct Mutex<T> {
/// Write guard for [`DebugRwLock`]. inner: sync::Mutex<T>,
#[cfg(debug_assertions)]
pub type DebugWriteGuard<'a, T> = TracingWriteGuard<'a, T>;
#[cfg(not(debug_assertions))]
pub type DebugWriteGuard<'a, T> = RwLockWriteGuard<'a, T>;
/// Debug-only tracing `Once`.
///
/// Type alias that resolves to [`TracingOnce`] when debug assertions are enabled and to
/// [`std::sync::Once`] when they're not. Use this if you want to have the benefits of cycle
/// detection in development but do not want to pay the performance penalty in release.
#[cfg(debug_assertions)]
pub type DebugOnce = TracingOnce;
#[cfg(not(debug_assertions))]
pub type DebugOnce = Once;
/// Wrapper for [`std::sync::Mutex`].
///
/// Refer to the [crate-level][`crate`] documentaiton for the differences between this struct and
/// the one it wraps.
#[derive(Debug, Default)]
pub struct TracingMutex<T> {
inner: Mutex<T>,
id: MutexId, id: MutexId,
} }
/// Wrapper for [`std::sync::MutexGuard`]. /// Wrapper for [`std::sync::MutexGuard`].
/// ///
/// Refer to the [crate-level][`crate`] documentaiton for the differences between this struct and /// Refer to the [crate-level][`crate`] documentation for the differences between this struct and
/// the one it wraps. /// the one it wraps.
#[derive(Debug)] #[derive(Debug)]
pub struct TracingMutexGuard<'a, T> { pub struct MutexGuard<'a, T> {
inner: MutexGuard<'a, T>, inner: sync::MutexGuard<'a, T>,
_mutex: BorrowedMutex<'a>, _mutex: BorrowedMutex<'a>,
} }
fn map_lockresult<T, I, F>(result: LockResult<I>, mapper: F) -> LockResult<T> fn map_lockresult<T, I, F>(result: LockResult<I>, mapper: F) -> LockResult<T>
where where
F: FnOnce(I) -> T, F: FnOnce(I) -> T,
{ {
match result { match result {
Ok(inner) => Ok(mapper(inner)), Ok(inner) => Ok(mapper(inner)),
Err(poisoned) => Err(PoisonError::new(mapper(poisoned.into_inner()))), Err(poisoned) => Err(PoisonError::new(mapper(poisoned.into_inner()))),
} }
} }
fn map_trylockresult<T, I, F>(result: TryLockResult<I>, mapper: F) -> TryLockResult<T> fn map_trylockresult<T, I, F>(result: TryLockResult<I>, mapper: F) -> TryLockResult<T>
where where
F: FnOnce(I) -> T, F: FnOnce(I) -> T,
{ {
match result { match result {
Ok(inner) => Ok(mapper(inner)), Ok(inner) => Ok(mapper(inner)),
Err(TryLockError::WouldBlock) => Err(TryLockError::WouldBlock), Err(TryLockError::WouldBlock) => Err(TryLockError::WouldBlock),
@@ -132,13 +85,13 @@ where
Err(PoisonError::new(mapper(poisoned.into_inner())).into()) Err(PoisonError::new(mapper(poisoned.into_inner())).into())
} }
} }
} }
impl<T> TracingMutex<T> { impl<T> Mutex<T> {
/// Create a new tracing mutex with the provided value. /// Create a new tracing mutex with the provided value.
pub fn new(t: T) -> Self { pub fn new(t: T) -> Self {
Self { Self {
inner: Mutex::new(t), inner: sync::Mutex::new(t),
id: MutexId::new(), id: MutexId::new(),
} }
} }
@@ -150,11 +103,11 @@ impl<T> TracingMutex<T> {
/// This method participates in lock dependency tracking. If acquiring this lock introduces a /// This method participates in lock dependency tracking. If acquiring this lock introduces a
/// dependency cycle, this method will panic. /// dependency cycle, this method will panic.
#[track_caller] #[track_caller]
pub fn lock(&self) -> LockResult<TracingMutexGuard<T>> { pub fn lock(&self) -> LockResult<MutexGuard<T>> {
let mutex = self.id.get_borrowed(); let mutex = self.id.get_borrowed();
let result = self.inner.lock(); let result = self.inner.lock();
let mapper = |guard| TracingMutexGuard { let mapper = |guard| MutexGuard {
_mutex: mutex, _mutex: mutex,
inner: guard, inner: guard,
}; };
@@ -169,11 +122,11 @@ impl<T> TracingMutex<T> {
/// This method participates in lock dependency tracking. If acquiring this lock introduces a /// This method participates in lock dependency tracking. If acquiring this lock introduces a
/// dependency cycle, this method will panic. /// dependency cycle, this method will panic.
#[track_caller] #[track_caller]
pub fn try_lock(&self) -> TryLockResult<TracingMutexGuard<T>> { pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
let mutex = self.id.get_borrowed(); let mutex = self.id.get_borrowed();
let result = self.inner.try_lock(); let result = self.inner.try_lock();
let mapper = |guard| TracingMutexGuard { let mapper = |guard| MutexGuard {
_mutex: mutex, _mutex: mutex,
inner: guard, inner: guard,
}; };
@@ -197,137 +150,132 @@ impl<T> TracingMutex<T> {
pub fn into_inner(self) -> LockResult<T> { pub fn into_inner(self) -> LockResult<T> {
self.inner.into_inner() self.inner.into_inner()
} }
} }
impl<T> From<T> for TracingMutex<T> { impl<T> From<T> for Mutex<T> {
fn from(t: T) -> Self { fn from(t: T) -> Self {
Self::new(t) Self::new(t)
} }
} }
impl<'a, T> Deref for TracingMutexGuard<'a, T> { impl<'a, T> Deref for MutexGuard<'a, T> {
type Target = T; type Target = T;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.inner &self.inner
} }
} }
impl<'a, T> DerefMut for TracingMutexGuard<'a, T> { impl<'a, T> DerefMut for MutexGuard<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner &mut self.inner
} }
} }
impl<'a, T: fmt::Display> fmt::Display for TracingMutexGuard<'a, T> { impl<'a, T: fmt::Display> fmt::Display for MutexGuard<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f) self.inner.fmt(f)
} }
} }
/// Wrapper around [`std::sync::Condvar`]. /// Wrapper around [`std::sync::Condvar`].
/// ///
/// Allows `TracingMutexGuard` to be used with a `Condvar`. Unlike other structs in this module, /// Allows `TracingMutexGuard` to be used with a `Condvar`. Unlike other structs in this module,
/// this wrapper does not add any additional dependency tracking or other overhead on top of the /// this wrapper does not add any additional dependency tracking or other overhead on top of the
/// primitive it wraps. All dependency tracking happens through the mutexes itself. /// primitive it wraps. All dependency tracking happens through the mutexes itself.
/// ///
/// # Panics /// # Panics
/// ///
/// This struct does not add any panics over the base implementation of `Condvar`, but panics due to /// This struct does not add any panics over the base implementation of `Condvar`, but panics due to
/// dependency tracking may poison associated mutexes. /// dependency tracking may poison associated mutexes.
/// ///
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use std::sync::Arc; /// use std::sync::Arc;
/// use std::thread; /// use std::thread;
/// ///
/// use tracing_mutex::stdsync::{TracingCondvar, TracingMutex}; /// use tracing_mutex::stdsync::tracing::{Condvar, Mutex};
/// ///
/// let pair = Arc::new((TracingMutex::new(false), TracingCondvar::new())); /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
/// let pair2 = Arc::clone(&pair); /// let pair2 = Arc::clone(&pair);
/// ///
/// // Spawn a thread that will unlock the condvar /// // Spawn a thread that will unlock the condvar
/// thread::spawn(move || { /// thread::spawn(move || {
/// let (lock, condvar) = &*pair2; /// let (lock, condvar) = &*pair2;
/// *lock.lock().unwrap() = true; /// *lock.lock().unwrap() = true;
/// condvar.notify_one(); /// condvar.notify_one();
/// }); /// });
/// ///
/// // Wait until the thread unlocks the condvar /// // Wait until the thread unlocks the condvar
/// let (lock, condvar) = &*pair; /// let (lock, condvar) = &*pair;
/// let guard = lock.lock().unwrap(); /// let guard = lock.lock().unwrap();
/// let guard = condvar.wait_while(guard, |started| !*started).unwrap(); /// let guard = condvar.wait_while(guard, |started| !*started).unwrap();
/// ///
/// // Guard should read true now /// // Guard should read true now
/// assert!(*guard); /// assert!(*guard);
/// ``` /// ```
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct TracingCondvar(Condvar); pub struct Condvar(sync::Condvar);
impl TracingCondvar { impl Condvar {
/// Creates a new condition variable which is ready to be waited on and notified. /// Creates a new condition variable which is ready to be waited on and notified.
pub fn new() -> Self { pub fn new() -> Self {
Default::default() Default::default()
} }
/// Wrapper for [`std::sync::Condvar::wait`]. /// Wrapper for [`std::sync::Condvar::wait`].
pub fn wait<'a, T>( pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
&self, let MutexGuard { _mutex, inner } = guard;
guard: TracingMutexGuard<'a, T>,
) -> LockResult<TracingMutexGuard<'a, T>> {
let TracingMutexGuard { _mutex, inner } = guard;
map_lockresult(self.0.wait(inner), |inner| TracingMutexGuard { map_lockresult(self.0.wait(inner), |inner| MutexGuard { _mutex, inner })
_mutex,
inner,
})
} }
/// Wrapper for [`std::sync::Condvar::wait_while`]. /// Wrapper for [`std::sync::Condvar::wait_while`].
pub fn wait_while<'a, T, F>( pub fn wait_while<'a, T, F>(
&self, &self,
guard: TracingMutexGuard<'a, T>, guard: MutexGuard<'a, T>,
condition: F, condition: F,
) -> LockResult<TracingMutexGuard<'a, T>> ) -> LockResult<MutexGuard<'a, T>>
where where
F: FnMut(&mut T) -> bool, F: FnMut(&mut T) -> bool,
{ {
let TracingMutexGuard { _mutex, inner } = guard; let MutexGuard { _mutex, inner } = guard;
map_lockresult(self.0.wait_while(inner, condition), |inner| { map_lockresult(self.0.wait_while(inner, condition), |inner| MutexGuard {
TracingMutexGuard { _mutex, inner } _mutex,
inner,
}) })
} }
/// Wrapper for [`std::sync::Condvar::wait_timeout`]. /// Wrapper for [`std::sync::Condvar::wait_timeout`].
pub fn wait_timeout<'a, T>( pub fn wait_timeout<'a, T>(
&self, &self,
guard: TracingMutexGuard<'a, T>, guard: MutexGuard<'a, T>,
dur: Duration, dur: Duration,
) -> LockResult<(TracingMutexGuard<'a, T>, WaitTimeoutResult)> { ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
let TracingMutexGuard { _mutex, inner } = guard; let MutexGuard { _mutex, inner } = guard;
map_lockresult(self.0.wait_timeout(inner, dur), |(inner, result)| { map_lockresult(self.0.wait_timeout(inner, dur), |(inner, result)| {
(TracingMutexGuard { _mutex, inner }, result) (MutexGuard { _mutex, inner }, result)
}) })
} }
/// Wrapper for [`std::sync::Condvar::wait_timeout_while`]. /// Wrapper for [`std::sync::Condvar::wait_timeout_while`].
pub fn wait_timeout_while<'a, T, F>( pub fn wait_timeout_while<'a, T, F>(
&self, &self,
guard: TracingMutexGuard<'a, T>, guard: MutexGuard<'a, T>,
dur: Duration, dur: Duration,
condition: F, condition: F,
) -> LockResult<(TracingMutexGuard<'a, T>, WaitTimeoutResult)> ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
where where
F: FnMut(&mut T) -> bool, F: FnMut(&mut T) -> bool,
{ {
let TracingMutexGuard { _mutex, inner } = guard; let MutexGuard { _mutex, inner } = guard;
map_lockresult( map_lockresult(
self.0.wait_timeout_while(inner, dur, condition), self.0.wait_timeout_while(inner, dur, condition),
|(inner, result)| (TracingMutexGuard { _mutex, inner }, result), |(inner, result)| (MutexGuard { _mutex, inner }, result),
) )
} }
@@ -340,33 +288,33 @@ impl TracingCondvar {
pub fn notify_all(&self) { pub fn notify_all(&self) {
self.0.notify_all(); self.0.notify_all();
} }
} }
/// Wrapper for [`std::sync::RwLock`]. /// Wrapper for [`std::sync::RwLock`].
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct TracingRwLock<T> { pub struct RwLock<T> {
inner: RwLock<T>, inner: sync::RwLock<T>,
id: MutexId, id: MutexId,
} }
/// Hybrid wrapper for both [`std::sync::RwLockReadGuard`] and [`std::sync::RwLockWriteGuard`]. /// Hybrid wrapper for both [`std::sync::RwLockReadGuard`] and [`std::sync::RwLockWriteGuard`].
/// ///
/// Please refer to [`TracingReadGuard`] and [`TracingWriteGuard`] for usable types. /// Please refer to [`RwLockReadGuard`] and [`RwLockWriteGuard`] for usable types.
#[derive(Debug)] #[derive(Debug)]
pub struct TracingRwLockGuard<'a, L> { pub struct TracingRwLockGuard<'a, L> {
inner: L, inner: L,
_mutex: BorrowedMutex<'a>, _mutex: BorrowedMutex<'a>,
} }
/// Wrapper around [`std::sync::RwLockReadGuard`]. /// Wrapper around [`std::sync::RwLockReadGuard`].
pub type TracingReadGuard<'a, T> = TracingRwLockGuard<'a, RwLockReadGuard<'a, T>>; pub type RwLockReadGuard<'a, T> = TracingRwLockGuard<'a, sync::RwLockReadGuard<'a, T>>;
/// Wrapper around [`std::sync::RwLockWriteGuard`]. /// Wrapper around [`std::sync::RwLockWriteGuard`].
pub type TracingWriteGuard<'a, T> = TracingRwLockGuard<'a, RwLockWriteGuard<'a, T>>; pub type RwLockWriteGuard<'a, T> = TracingRwLockGuard<'a, sync::RwLockWriteGuard<'a, T>>;
impl<T> TracingRwLock<T> { impl<T> RwLock<T> {
pub fn new(t: T) -> Self { pub fn new(t: T) -> Self {
Self { Self {
inner: RwLock::new(t), inner: sync::RwLock::new(t),
id: MutexId::new(), id: MutexId::new(),
} }
} }
@@ -378,7 +326,7 @@ impl<T> TracingRwLock<T> {
/// This method participates in lock dependency tracking. If acquiring this lock introduces a /// This method participates in lock dependency tracking. If acquiring this lock introduces a
/// dependency cycle, this method will panic. /// dependency cycle, this method will panic.
#[track_caller] #[track_caller]
pub fn read(&self) -> LockResult<TracingReadGuard<T>> { pub fn read(&self) -> LockResult<RwLockReadGuard<T>> {
let mutex = self.id.get_borrowed(); let mutex = self.id.get_borrowed();
let result = self.inner.read(); let result = self.inner.read();
@@ -395,7 +343,7 @@ impl<T> TracingRwLock<T> {
/// This method participates in lock dependency tracking. If acquiring this lock introduces a /// This method participates in lock dependency tracking. If acquiring this lock introduces a
/// dependency cycle, this method will panic. /// dependency cycle, this method will panic.
#[track_caller] #[track_caller]
pub fn write(&self) -> LockResult<TracingWriteGuard<T>> { pub fn write(&self) -> LockResult<RwLockWriteGuard<T>> {
let mutex = self.id.get_borrowed(); let mutex = self.id.get_borrowed();
let result = self.inner.write(); let result = self.inner.write();
@@ -412,7 +360,7 @@ impl<T> TracingRwLock<T> {
/// This method participates in lock dependency tracking. If acquiring this lock introduces a /// This method participates in lock dependency tracking. If acquiring this lock introduces a
/// dependency cycle, this method will panic. /// dependency cycle, this method will panic.
#[track_caller] #[track_caller]
pub fn try_read(&self) -> TryLockResult<TracingReadGuard<T>> { pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<T>> {
let mutex = self.id.get_borrowed(); let mutex = self.id.get_borrowed();
let result = self.inner.try_read(); let result = self.inner.try_read();
@@ -429,7 +377,7 @@ impl<T> TracingRwLock<T> {
/// This method participates in lock dependency tracking. If acquiring this lock introduces a /// This method participates in lock dependency tracking. If acquiring this lock introduces a
/// dependency cycle, this method will panic. /// dependency cycle, this method will panic.
#[track_caller] #[track_caller]
pub fn try_write(&self) -> TryLockResult<TracingWriteGuard<T>> { pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<T>> {
let mutex = self.id.get_borrowed(); let mutex = self.id.get_borrowed();
let result = self.inner.try_write(); let result = self.inner.try_write();
@@ -450,49 +398,49 @@ impl<T> TracingRwLock<T> {
pub fn into_inner(self) -> LockResult<T> { pub fn into_inner(self) -> LockResult<T> {
self.inner.into_inner() self.inner.into_inner()
} }
} }
impl<T> From<T> for TracingRwLock<T> { impl<T> From<T> for RwLock<T> {
fn from(t: T) -> Self { fn from(t: T) -> Self {
Self::new(t) Self::new(t)
} }
} }
impl<'a, L, T> Deref for TracingRwLockGuard<'a, L> impl<'a, L, T> Deref for TracingRwLockGuard<'a, L>
where where
L: Deref<Target = T>, L: Deref<Target = T>,
{ {
type Target = T; type Target = T;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
self.inner.deref() self.inner.deref()
} }
} }
impl<'a, T, L> DerefMut for TracingRwLockGuard<'a, L> impl<'a, T, L> DerefMut for TracingRwLockGuard<'a, L>
where where
L: Deref<Target = T> + DerefMut, L: Deref<Target = T> + DerefMut,
{ {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
self.inner.deref_mut() self.inner.deref_mut()
} }
} }
/// Wrapper around [`std::sync::Once`]. /// Wrapper around [`std::sync::Once`].
/// ///
/// Refer to the [crate-level][`crate`] documentaiton for the differences between this struct and /// Refer to the [crate-level][`crate`] documentaiton for the differences between this struct and
/// the one it wraps. /// the one it wraps.
#[derive(Debug)] #[derive(Debug)]
pub struct TracingOnce { pub struct Once {
inner: Once, inner: sync::Once,
mutex_id: LazyMutexId, mutex_id: LazyMutexId,
} }
impl TracingOnce { impl Once {
/// Create a new `Once` value. /// Create a new `Once` value.
pub const fn new() -> Self { pub const fn new() -> Self {
Self { Self {
inner: Once::new(), inner: sync::Once::new(),
mutex_id: LazyMutexId::new(), mutex_id: LazyMutexId::new(),
} }
} }
@@ -511,7 +459,7 @@ impl TracingOnce {
self.inner.call_once(f); self.inner.call_once(f);
} }
/// Performs the same operation as [`call_once`][TracingOnce::call_once] except it ignores /// Performs the same operation as [`call_once`][Once::call_once] except it ignores
/// poisoning. /// poisoning.
/// ///
/// # Panics /// # Panics
@@ -530,10 +478,10 @@ impl TracingOnce {
pub fn is_completed(&self) -> bool { pub fn is_completed(&self) -> bool {
self.inner.is_completed() self.inner.is_completed()
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::Arc; use std::sync::Arc;
use std::thread; use std::thread;
@@ -541,7 +489,7 @@ mod tests {
#[test] #[test]
fn test_mutex_usage() { fn test_mutex_usage() {
let mutex = Arc::new(TracingMutex::new(0)); let mutex = Arc::new(Mutex::new(0));
assert_eq!(*mutex.lock().unwrap(), 0); assert_eq!(*mutex.lock().unwrap(), 0);
*mutex.lock().unwrap() = 1; *mutex.lock().unwrap() = 1;
@@ -563,7 +511,7 @@ mod tests {
#[test] #[test]
fn test_rwlock_usage() { fn test_rwlock_usage() {
let rwlock = Arc::new(TracingRwLock::new(0)); let rwlock = Arc::new(RwLock::new(0));
assert_eq!(*rwlock.read().unwrap(), 0); assert_eq!(*rwlock.read().unwrap(), 0);
assert_eq!(*rwlock.write().unwrap(), 0); assert_eq!(*rwlock.write().unwrap(), 0);
@@ -590,7 +538,7 @@ mod tests {
#[test] #[test]
fn test_once_usage() { fn test_once_usage() {
let once = Arc::new(TracingOnce::new()); let once = Arc::new(Once::new());
let once_clone = once.clone(); let once_clone = once.clone();
assert!(!once.is_completed()); assert!(!once.is_completed());
@@ -611,8 +559,8 @@ mod tests {
#[test] #[test]
#[should_panic(expected = "Mutex order graph should not have cycles")] #[should_panic(expected = "Mutex order graph should not have cycles")]
fn test_detect_cycle() { fn test_detect_cycle() {
let a = TracingMutex::new(()); let a = Mutex::new(());
let b = TracingMutex::new(()); let b = Mutex::new(());
let hold_a = a.lock().unwrap(); let hold_a = a.lock().unwrap();
let _ = b.lock(); let _ = b.lock();
@@ -622,4 +570,5 @@ mod tests {
let _hold_b = b.lock().unwrap(); let _hold_b = b.lock().unwrap();
let _ = a.lock(); let _ = a.lock();
} }
}
} }