use core::mem::ManuallyDrop;
use crate::{DispatchObject, DispatchRetained};
use crate::{DispatchTime, WaitError};
dispatch_object!(
#[doc(alias = "dispatch_semaphore_t")]
#[doc(alias = "dispatch_semaphore_s")]
pub struct DispatchSemaphore;
);
dispatch_object_not_data!(unsafe DispatchSemaphore);
impl DispatchSemaphore {
pub fn try_acquire(&self, timeout: DispatchTime) -> Result<DispatchSemaphoreGuard, WaitError> {
let result = Self::wait(self, timeout);
match result {
0 => Ok(DispatchSemaphoreGuard(self.retain())),
_ => Err(WaitError::Timeout),
}
}
}
#[derive(Debug)]
pub struct DispatchSemaphoreGuard(DispatchRetained<DispatchSemaphore>);
impl DispatchSemaphoreGuard {
pub fn release(self) -> bool {
let this = ManuallyDrop::new(self);
let result = this.0.signal();
result != 0
}
}
impl Drop for DispatchSemaphoreGuard {
fn drop(&mut self) {
self.0.signal();
}
}