use std::ops::{Deref, DerefMut};
use foreign_types::ForeignTypeRef;
use crate::cfile::CFileRef;
pub struct FileLock<'a>(&'a mut CFileRef);
impl<'a> Drop for FileLock<'a> {
fn drop(&mut self) {
unsafe { funlockfile(self.0.as_ptr()) }
}
}
impl<'a> Deref for FileLock<'a> {
type Target = CFileRef;
fn deref(&self) -> &Self::Target {
self.0
}
}
impl<'a> DerefMut for FileLock<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0
}
}
impl CFileRef {
pub fn lock(&mut self) -> FileLock {
unsafe { flockfile(self.as_ptr()) }
FileLock(self)
}
pub fn try_lock(&mut self) -> Option<FileLock> {
if unsafe { ftrylockfile(self.as_ptr()) } == 0 {
Some(FileLock(self))
} else {
None
}
}
}
extern "C" {
fn flockfile(file: *mut libc::FILE);
fn ftrylockfile(file: *mut libc::FILE) -> i32;
fn funlockfile(file: *mut libc::FILE);
}