Skip to content

Commit

Permalink
feat(maitake-sync): impl Default for locks (#473)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
hawkw committed Jan 27, 2024
1 parent 98b362a commit 6adf597
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
8 changes: 7 additions & 1 deletion maitake-sync/src/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ impl<T: ?Sized> Mutex<T> {
/// # 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);
/// ```
Expand All @@ -268,6 +268,12 @@ impl<T: ?Sized> Mutex<T> {
}
}

impl<T: Default> Default for Mutex<T> {
fn default() -> Self {
Self::new(Default::default())
}
}

impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { data: _, wait } = self;
Expand Down
6 changes: 6 additions & 0 deletions maitake-sync/src/rwlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,12 @@ impl<T: ?Sized> RwLock<T> {
}
}

impl<T: Default> Default for RwLock<T> {
fn default() -> Self {
Self::new(Default::default())
}
}

impl<T: ?Sized + fmt::Debug> fmt::Debug for RwLock<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { sem, data: _ } = self;
Expand Down
6 changes: 6 additions & 0 deletions maitake-sync/src/spin/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,12 @@ impl<T> Mutex<T> {
}
}

impl<T: Default> Default for Mutex<T> {
fn default() -> Self {
Self::new(Default::default())
}
}

unsafe impl<T: Send> Send for Mutex<T> {}
unsafe impl<T: Send> Sync for Mutex<T> {}

Expand Down

0 comments on commit 6adf597

Please sign in to comment.