Skip to content

feat: define MappedSpinlockGuard #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@
/// The spinlock implemenation is based on the abstractions provided by the `lock_api` crate.
pub use lock_api;

pub use spinlock::{const_spinlock, RawSpinlock, Spinlock, SpinlockGuard};
pub use spinlock::{const_spinlock, MappedSpinlockGuard, RawSpinlock, Spinlock, SpinlockGuard};

mod spinlock;
40 changes: 40 additions & 0 deletions src/spinlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,33 @@ pub type Spinlock<T> = lock_api::Mutex<RawSpinlock, T>;
/// assert!(spinlock.try_lock().is_some());
pub type SpinlockGuard<'a, T> = lock_api::MutexGuard<'a, RawSpinlock, T>;

/// A RAII guard returned by `SpinlockGuard::map`.
///
/// ## Example
/// ```rust
/// use spinning_top::{MappedSpinlockGuard, Spinlock, SpinlockGuard};
///
/// let spinlock = Spinlock::new(Some(3));
///
/// // Begin a new scope.
/// {
/// // Lock the spinlock to create a `SpinlockGuard`.
/// let mut guard: SpinlockGuard<_> = spinlock.lock();
///
/// // Map the internal value of `gurad`. `guard` is moved.
/// let mut mapped: MappedSpinlockGuard<'_, _> =
/// SpinlockGuard::map(guard, |g| g.as_mut().unwrap());
/// assert_eq!(*mapped, 3);
///
/// *mapped = 5;
/// assert_eq!(*mapped, 5);
/// } // `mapped` is dropped -> frees the spinlock again.
///
/// // The operation is reflected to the original lock.
/// assert_eq!(*spinlock.lock(), Some(5));
/// ```
pub type MappedSpinlockGuard<'a, T> = lock_api::MappedMutexGuard<'a, RawSpinlock, T>;

/// Create an unlocked `Spinlock` in a `const` context.
///
/// ## Example
Expand Down Expand Up @@ -215,4 +242,17 @@ mod tests {
core::mem::drop(data3);
assert!(spinlock3.try_lock().is_some());
}

#[test]
fn mapped_lock() {
let spinlock = Spinlock::new([1, 2, 3]);
let data = spinlock.lock();
let mut mapped = SpinlockGuard::map(data, |d| &mut d[0]);
assert_eq!(*mapped, 1);
*mapped = 4;
assert_eq!(*mapped, 4);
core::mem::drop(mapped);
assert!(!spinlock.is_locked());
assert_eq!(*spinlock.lock(), [4, 2, 3]);
}
}