pub struct Mutex<T>(spin::Mutex<T>);
pub type MutexGuard<'a, T> = spin::MutexGuard<'a, T>;
impl<T> Mutex<T> {
pub const fn new(data: T) -> Self {
Mutex(spin::Mutex::new(data))
}
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
self.0.try_lock()
}
#[track_caller]
pub fn lock(&self) -> MutexGuard<'_, T> {
self.try_lock().unwrap()
}
pub fn into_inner(self) -> T {
self.0.into_inner()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn static_mutex() {
static MUTEX: Mutex<i32> = Mutex::new(42);
*MUTEX.lock() = 13;
assert_eq!(*MUTEX.lock(), 13);
}
#[test]
#[should_panic]
fn double_lock() {
let mutex = Mutex::new(42);
let _guard = mutex.lock();
mutex.lock();
}
}