use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{LockFile, LockFileEx, UnlockFile, LOCKFILE_EXCLUSIVE_LOCK};
use std::ops;
#[inline]
pub fn lock(handle: RawHandle) -> Result<LockGuard, Error> {
if unsafe { LockFile(handle, 0, 0, 1, 0) } {
Ok(LockGuard { handle })
} else {
Err(ErrorKind::Locked.into())
}
}
#[inline]
fn unlock(handle: HANDLE) -> Result<(), Error> {
if unsafe { UnlockFile(handle, 0, 0, 1, 0) } {
Ok(())
} else {
Err(ErrorKind::Locked.into())
}
}
#[derive(Debug)]
pub struct FdLockGuard<'fdlock, T: AsRawHandle> {
lock: &'fdlock mut FdLock<T>,
}
impl<T: AsRawHandle> ops::Deref for FdLockGuard<'_, T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
&self.lock.t
}
}
impl<T: AsRawHandle> ops::DerefMut for FdLockGuard<'_, T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.lock.t
}
}
impl<T: AsRawHandle> Drop for FdLockGuard<'_, T> {
#[inline]
fn drop(&mut self) {
let fd = self.lock.t.as_raw_fd();
if unsafe { !UnlockFile(handle, 0, 0, 1, 0) } {
panic!("Could not unlock the file descriptor");
}
}
}
#[derive(Debug)]
pub struct FdLock<T: AsRawHandle> {
t: T
}
impl<T: AsRawHandle> FdLock<T> {
#[inline]
pub fn new(t: T) -> Self {
FdLock { t }
}
#[inline]
pub fn lock(&mut self) -> Result<FdLockGuard<'_, T>, Error> {
let fd = self.t.as_raw_fd();
if unsafe { LockFileEx(handle, LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0) } {
Ok(FdLockGuard { lock: self })
} else {
Err(ErrorKind::Other.into())
}
}
#[inline]
pub fn try_lock(&mut self) -> Result<FdLockGuard<'_, T>, Error> {
let fd = self.t.as_raw_fd();
if unsafe { LockFile(handle, 0, 0, 1, 0) } {
Ok(FdLockGuard { lock: self })
} else {
Err(ErrorKind::Other.into())
}
}
}