Last active
February 2, 2024 17:00
-
-
Save eloff/345f08265b9084661b22a87158b14aac to your computer and use it in GitHub Desktop.
Rust Mutex for when you don't need poisoning
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard}; | |
use std::sync::{TryLockError, Mutex, RwLock}; | |
pub struct SimpleMutex<T>(Mutex<T>); | |
impl<T> SimpleMutex<T> { | |
pub const fn new(t: T) -> Self { | |
Self(Mutex::new(t)) | |
} | |
pub fn lock(&self) -> MutexGuard<'_, T> { | |
self.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) | |
} | |
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> { | |
match self.0.try_lock() { | |
Ok(guard) => Some(guard), | |
Err(TryLockError::WouldBlock) => None, | |
Err(TryLockError::Poisoned(err)) => Some(err.into_inner()), | |
} | |
} | |
pub fn unlock(&self, guard: MutexGuard<'_, T>) { | |
drop(guard); | |
} | |
pub fn get_mut(&mut self) -> &mut T { | |
self.0.get_mut().unwrap_or_else(|poisoned| poisoned.into_inner()) | |
} | |
} | |
pub struct SimpleRwLock<T>(RwLock<T>); | |
impl<T> SimpleRwLock<T> { | |
pub const fn new(t: T) -> Self { | |
Self(RwLock::new(t)) | |
} | |
pub fn read(&self) -> RwLockReadGuard<'_, T> { | |
self.0.read().unwrap_or_else(|poisoned| poisoned.into_inner()) | |
} | |
pub fn try_read(&self) -> Option<RwLockReadGuard<'_, T>> { | |
match self.0.try_read() { | |
Ok(guard) => Some(guard), | |
Err(TryLockError::WouldBlock) => None, | |
Err(TryLockError::Poisoned(err)) => Some(err.into_inner()), | |
} | |
} | |
pub fn write(&self) -> RwLockWriteGuard<'_, T> { | |
self.0.write().unwrap_or_else(|poisoned| poisoned.into_inner()) | |
} | |
pub fn try_write(&self) -> Option<RwLockWriteGuard<'_, T>> { | |
match self.0.try_write() { | |
Ok(guard) => Some(guard), | |
Err(TryLockError::WouldBlock) => None, | |
Err(TryLockError::Poisoned(err)) => Some(err.into_inner()), | |
} | |
} | |
pub fn unlock_read(&self, guard: RwLockReadGuard<'_, T>) { | |
drop(guard); | |
} | |
pub fn unlock_write(&self, guard: RwLockWriteGuard<'_, T>) { | |
drop(guard); | |
} | |
pub fn get_mut(&mut self) -> &mut T { | |
self.0.get_mut().unwrap_or_else(|poisoned| poisoned.into_inner()) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment