wasefire_sync/mutex.rs
1// Copyright 2023 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/// Non-blocking non-reentrant mutex.
16///
17/// Locking this mutex will panic if it is already locked. In particular, it will not block.
18pub struct Mutex<T>(spin::Mutex<T>);
19
20/// Locks a mutex and provides access to its content until dropped.
21pub type MutexGuard<'a, T> = spin::MutexGuard<'a, T>;
22
23impl<T> Mutex<T> {
24 /// Creates a new mutex.
25 pub const fn new(data: T) -> Self {
26 Mutex(spin::Mutex::new(data))
27 }
28
29 /// Tries to lock the mutex.
30 pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
31 self.0.try_lock()
32 }
33
34 /// Locks the mutex.
35 ///
36 /// # Panics
37 ///
38 /// Panics if it is already locked.
39 #[track_caller]
40 pub fn lock(&self) -> MutexGuard<'_, T> {
41 self.try_lock().unwrap()
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48
49 #[test]
50 fn static_mutex() {
51 static MUTEX: Mutex<i32> = Mutex::new(42);
52 *MUTEX.lock() = 13;
53 assert_eq!(*MUTEX.lock(), 13);
54 }
55
56 #[test]
57 #[should_panic]
58 fn double_lock() {
59 let mutex = Mutex::new(42);
60 let _guard = mutex.lock();
61 mutex.lock();
62 }
63}