1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Provides a mutex that can be closed for long-term access.
//!
//! This is useful if you have an object that is in one of two states: a
//! concurrent state, where it can be accessed by multiple users, and a
//! non-concurrent state, where it can only be accessed by one user.
//!
//! In the non-concurrent state, you can close the mutex guarding the object so
//! that it can be accessed freely without additional locking, allowing it to be
//! used in `async` functions (for example). When the object is to reenter the
//! concurrent state, you can open the mutex, allowing normal mutex operations.
//!
//! Something similar to this can be achieved with an ordinary mutex by holding
//! the lock for the lifetime of the non-concurrent state, but this means that
//! any other attempt to lock the mutex will hang for an indefinite period of
//! time, possibly deadlocking. `try_lock` cannot be used to overcome this,
//! because it would also fail while in the concurrent state with multiple
//! concurrent accessors competing for the lock.

// UNSAFETY: unsafe needed to implement interior mutability to locked values.
#![allow(unsafe_code)]
#![warn(missing_docs)]

use parking_lot::Mutex;
use parking_lot::MutexGuard;
use std::cell::UnsafeCell;
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::ops::DerefMut;
use std::sync::Arc;

/// A mutex that can be _closed_.
///
/// A closed mutex can be accessed freely by the owner, but while closed it
/// cannot be locked by anyone else.
pub struct CloseableMutex<T: ?Sized> {
    mutex: Mutex<bool>,
    value: UnsafeCell<T>,
}

// SAFETY: `mutex` ensures that there is only a single concurrent access to
// `value`, providing `Sync` as long as `T` is `Send`.
unsafe impl<T: ?Sized + Send> Sync for CloseableMutex<T> {}

impl<T> CloseableMutex<T> {
    /// Returns a new instance wrapping the given value.
    pub fn new(value: T) -> Self {
        Self {
            mutex: Mutex::new(false),
            value: value.into(),
        }
    }
}

impl<T: ?Sized> CloseableMutex<T> {
    /// Closes the mutex, returning a guard that can be used to access the
    /// underlying value.
    ///
    /// When the guard is dropped, the mutex is re-opened.
    ///
    /// While the mutex is closed, calls to `lock_if_open` will return `None`,
    /// and calls to `lock` will panic.
    pub fn close(self: Arc<Self>) -> ClosedGuard<T> {
        {
            let mut closed = self.mutex.lock();
            assert!(!*closed, "object is already closed");
            *closed = true;
        }
        ClosedGuard(ManuallyDrop::new(self))
    }

    /// If the lock is open, waits for it to become available and returns a
    /// guard that can be used to access the underlying value.
    ///
    /// If the lock is closed, returns `None`.
    pub fn lock_if_open(&self) -> Option<OpenGuard<'_, T>> {
        let closed = self.mutex.lock();
        if *closed {
            return None;
        }
        MutexGuard::leak(closed);
        Some(OpenGuard(self))
    }

    /// Waits for the lock to become available and returns a guard that can be
    /// used to access the underlying value.
    ///
    /// # Panics
    /// Panics if the lock is closed. To avoid this, use `lock_if_open`.
    #[track_caller]
    pub fn lock(&self) -> OpenGuard<'_, T> {
        self.lock_if_open().expect("lock should not be closed")
    }
}

/// A guard that can be used to access the underlying value of a
/// [`CloseableMutex`].
#[must_use]
pub struct OpenGuard<'a, T: ?Sized>(&'a CloseableMutex<T>);

impl<T: ?Sized> Drop for OpenGuard<'_, T> {
    fn drop(&mut self) {
        // SAFETY: the mutex is known to be locked.
        unsafe {
            self.0.mutex.force_unlock();
        }
    }
}

impl<T: ?Sized> Deref for OpenGuard<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        // SAFETY: the mutex is known to be locked.
        unsafe { &*self.0.value.get() }
    }
}

impl<T: ?Sized> DerefMut for OpenGuard<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        // SAFETY: the mutex is known to be locked.
        unsafe { &mut *self.0.value.get() }
    }
}

/// A guard that can be used to access the underlying value of a
/// [`CloseableMutex`] while it is closed.
///
/// This wraps an [`Arc`] so that you can keep the mutex closed
/// for an unbounded period without having to deal with a lifetime.
// TODO: if this Arc-based functionality is not used or is otherwise
// inconvenient, then replace or augment this with a standard
// lifetime-based lock.
#[must_use]
pub struct ClosedGuard<T: ?Sized>(ManuallyDrop<Arc<CloseableMutex<T>>>);

impl<T: ?Sized> Drop for ClosedGuard<T> {
    fn drop(&mut self) {
        // SAFETY: this has not been called yet
        unsafe { self.release_ownership() };
    }
}

impl<T: ?Sized> ClosedGuard<T> {
    /// Opens the mutex, returning the inner instance.
    pub fn open(mut self) -> Arc<CloseableMutex<T>> {
        // SAFETY: this has not yet been called and will not be called again due
        // to the `forget`.
        let v = unsafe { self.release_ownership() };
        std::mem::forget(self);
        v
    }

    /// # Safety
    ///
    /// This must be called exactly once.
    unsafe fn release_ownership(&mut self) -> Arc<CloseableMutex<T>> {
        let was_owned = std::mem::replace(&mut *self.0.mutex.lock(), false);
        assert!(was_owned);
        // SAFETY: this is called exactly once.
        unsafe { ManuallyDrop::take(&mut self.0) }
    }
}

impl<T: ?Sized> Deref for ClosedGuard<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        // SAFETY: the mutex is known to be closed.
        unsafe { &*self.0.value.get() }
    }
}

impl<T: ?Sized> DerefMut for ClosedGuard<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        // SAFETY: the mutex is known to be closed.
        unsafe { &mut *self.0.value.get() }
    }
}

#[cfg(test)]
mod tests {
    use crate::CloseableMutex;
    use std::sync::Arc;

    #[test]
    fn test_mutex() {
        let x = Arc::new(CloseableMutex::new(0));
        *x.lock() = 5;
        *x.lock() = 6;
        assert_eq!(*x.lock(), 6);

        // Close the mutex, make sure locks are disallowed.
        {
            let mut c = x.clone().close();
            *c = 7;
            assert!(x.lock_if_open().is_none());
        }

        // Locks are allowed again.
        assert_eq!(*x.lock_if_open().unwrap(), 7);
        assert_eq!(*x.lock(), 7);
    }

    #[test]
    #[should_panic]
    fn test_closed_mutex_panics() {
        let x = Arc::new(CloseableMutex::new(0));
        let _c = x.clone().close();
        let _ = x.lock();
    }
}