use std::io::{Error, ErrorKind};
use std::ops;
use std::os::windows::io::AsRawHandle;
use winapi::um::fileapi::{LockFile, UnlockFile};
#[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 handle = self.lock.t.as_raw_handle();
if unsafe { !UnlockFile(handle, 0, 0, 1, 0) } == 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 try_lock(&mut self) -> Result<FdLockGuard<'_, T>, Error> {
let handle = self.t.as_raw_handle();
if unsafe { LockFile(handle, 0, 0, 1, 0) } == 0 {
Err(ErrorKind::Other.into())
} else {
Ok(FdLockGuard { lock: self })
}
}
}