Skip to content

Instantly share code, notes, and snippets.

@eloff
Last active February 2, 2024 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eloff/345f08265b9084661b22a87158b14aac to your computer and use it in GitHub Desktop.
Save eloff/345f08265b9084661b22a87158b14aac to your computer and use it in GitHub Desktop.
Rust Mutex for when you don't need poisoning
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