From 7c4333a134b909b213e9cfde388438547529ffbc Mon Sep 17 00:00:00 2001 From: Eliza Weisman Date: Sat, 27 Jan 2024 12:33:46 -0800 Subject: [PATCH] feat(maitake-sync): impl `Default` for locks (#473) This commit adds `Default` impls to `Mutex`, `RwLock`, and `spin::Mutex` where `T: Default`, allowing locked data to be constructed through `Default` without needing `Mutex::new(Default::default())` or similar. An implementation of `Default` for `spin::RwLock` was not added, because I already did that in #472. --- maitake-sync/src/mutex.rs | 8 +++++++- maitake-sync/src/rwlock.rs | 6 ++++++ maitake-sync/src/spin/mutex.rs | 6 ++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/maitake-sync/src/mutex.rs b/maitake-sync/src/mutex.rs index c3e7ef4e..5226731a 100644 --- a/maitake-sync/src/mutex.rs +++ b/maitake-sync/src/mutex.rs @@ -242,7 +242,7 @@ impl Mutex { /// # Examples /// /// ``` - /// let mut lock = maitake_sync::Mutex::new(0); + /// let mut lock = maitake_sync::spin::Mutex::new(0); /// *lock.get_mut() = 10; /// assert_eq!(*lock.try_lock().unwrap(), 10); /// ``` @@ -268,6 +268,12 @@ impl Mutex { } } +impl Default for Mutex { + fn default() -> Self { + Self::new(Default::default()) + } +} + impl fmt::Debug for Mutex { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { data: _, wait } = self; diff --git a/maitake-sync/src/rwlock.rs b/maitake-sync/src/rwlock.rs index fad12189..dc192b1b 100644 --- a/maitake-sync/src/rwlock.rs +++ b/maitake-sync/src/rwlock.rs @@ -431,6 +431,12 @@ impl RwLock { } } +impl Default for RwLock { + fn default() -> Self { + Self::new(Default::default()) + } +} + impl fmt::Debug for RwLock { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { sem, data: _ } = self; diff --git a/maitake-sync/src/spin/mutex.rs b/maitake-sync/src/spin/mutex.rs index 8bc165a5..ba88a43f 100644 --- a/maitake-sync/src/spin/mutex.rs +++ b/maitake-sync/src/spin/mutex.rs @@ -169,6 +169,12 @@ impl Mutex { } } +impl Default for Mutex { + fn default() -> Self { + Self::new(Default::default()) + } +} + unsafe impl Send for Mutex {} unsafe impl Sync for Mutex {}