summaryrefslogtreecommitdiff
path: root/src/collection/owned.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/collection/owned.rs')
-rwxr-xr-xsrc/collection/owned.rs40
1 files changed, 34 insertions, 6 deletions
diff --git a/src/collection/owned.rs b/src/collection/owned.rs
index 07a5402..483bc09 100755
--- a/src/collection/owned.rs
+++ b/src/collection/owned.rs
@@ -1,4 +1,4 @@
-use crate::iterator::LockContext;
+use crate::context::LockContext;
use crate::lockable::{
Lockable, LockableGetMut, LockableIntoInner, OwnedLockable, RawLock, Sharable,
};
@@ -61,7 +61,7 @@ unsafe impl<L: Lockable> Lockable for OwnedLockCollection<L> {
where
Self: 'a;
- #[mutants::skip] // It's hard to test lkocks in an OwnedLockCollection, because they're owned
+ #[mutants::skip] // It's hard to test locks in an OwnedLockCollection, because they're owned
#[cfg(not(tarpaulin_include))]
fn get_ptrs<'a>(&'a self, ptrs: &mut Vec<&'a dyn RawLock>) {
// It's ok to use self here, because the values in the collection already
@@ -350,6 +350,38 @@ impl<L: OwnedLockable> OwnedLockCollection<L> {
Ok(LockGuard { guard, key })
}
+ /// Creates a context that can be used to iterate over the items in order.
+ ///
+ /// Sometimes, partial allocation of locks is useful. For example, you may
+ /// want to acquire a lock on the first element of a list before deciding if
+ /// the second element should be locked. This function creates a
+ /// [`LockContext`] which is capable of doing exactly that.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// use happylock::{Mutex, ThreadKey};
+ /// use happylock::collection::OwnedLockCollection;
+ ///
+ /// let key = ThreadKey::get().unwrap();
+ /// let data = (Mutex::new(true), Mutex::new(42), Mutex::new(67));
+ /// let locks = OwnedLockCollection::new(data);
+ /// let mut ctx = locks.context();
+ /// let tuple = ctx.tuple(key);
+ ///
+ /// let (use_other, tuple) = tuple.lock_0();
+ /// let number = if **use_other {
+ /// tuple.lock_2().0
+ /// } else {
+ /// tuple.lock_1().0
+ /// };
+ /// assert_eq!(**number, 67);
+ /// ```
+ #[must_use]
+ pub const fn context(&self) -> LockContext<'_, L> {
+ LockContext::new(&self.child)
+ }
+
/// Unlocks the underlying lockable data type, returning the key that's
/// associated with it.
///
@@ -559,10 +591,6 @@ impl<L: Sharable> OwnedLockCollection<L> {
}
impl<L> OwnedLockCollection<L> {
- pub const fn context(&self) -> LockContext<'_, L> {
- LockContext::new(&self.child)
- }
-
/// Gets the underlying collection, consuming this collection.
///
/// # Examples