use crate::{
private::Sealed,
time::{Duration, Instant},
};
pub trait RawMutex: Sealed {
const NEW: Self;
fn lock(&self);
fn try_lock(&self) -> bool;
unsafe fn unlock(&self);
fn is_locked(&self) -> bool {
let was_acquired = self.try_lock();
if was_acquired {
unsafe { self.unlock() };
}
!was_acquired
}
}
pub trait RawMutexTimed: RawMutex {
fn try_lock_for(&self, timeout: Duration) -> bool;
#[inline]
fn try_lock_until(&self, timeout: Instant) -> bool {
let now = Instant::now();
let duration = timeout.duration_since(now);
if duration.is_zero() {
false
} else {
self.try_lock_for(duration)
}
}
}
pub trait RawRwLock: Sealed {
const NEW: Self;
fn read(&self);
fn try_read(&self) -> bool;
fn write(&self);
fn try_write(&self) -> bool;
unsafe fn read_unlock(&self);
unsafe fn write_unlock(&self);
unsafe fn downgrade(&self);
#[inline]
fn is_locked(&self) -> bool {
let acquired_lock = self.try_write();
if acquired_lock {
unsafe {
self.write_unlock();
}
}
!acquired_lock
}
fn is_locked_exclusive(&self) -> bool {
let acquired_lock = self.try_read();
if acquired_lock {
unsafe {
self.write_unlock();
}
}
!acquired_lock
}
}
pub trait RawRwLockTimed: RawRwLock {
fn try_read_for(&self, timeout: Duration) -> bool;
fn try_read_until(&self, timeout: Instant) -> bool {
let now = Instant::now();
let duration = timeout.duration_since(now);
if duration.is_zero() {
false
} else {
self.try_read_for(duration)
}
}
fn try_write_for(&self, timeout: Duration) -> bool;
fn try_write_until(&self, timeout: Instant) -> bool {
let now = Instant::now();
let duration = timeout.duration_since(now);
if duration.is_zero() {
false
} else {
self.try_write_for(duration)
}
}
}