Attempt to fix flocks on windows with unlock field

It seems that on Windows unlocking errors if the file has already been
unlocked. To fix this, we've added a platform-specific field to see if
the FileLock object has already been used to unlock the file.
This is the unlock field. In the Drop impl for Windows, we check the
unlocked flag to determine if we need to unlock the file.
next
Sayan Nandan 3 years ago
parent 79a7cfd2c2
commit 7777d1ee96

@ -52,6 +52,8 @@ use std::io::Write;
///
pub struct FileLock {
file: File,
#[cfg(windows)]
unlocked: bool,
}
impl FileLock {
@ -62,26 +64,47 @@ impl FileLock {
.write(true)
.open(filename)?;
Self::_lock(&file)?;
Ok(Self { file })
Ok(Self {
file,
#[cfg(windows)]
unlocked: false,
})
}
fn _lock(file: &File) -> Result<()> {
__sys::try_lock_ex(file)
}
pub fn unlock(&self) -> Result<()> {
#[cfg(not(windows))]
pub fn unlock(&mut self) -> Result<()> {
__sys::unlock_file(&self.file)
}
#[cfg(windows)]
pub fn unlock(&mut self) -> Result<()> {
__sys::unlock_file(&self.file)?;
self.unlocked = true;
Ok(())
}
pub fn write(&mut self, bytes: &[u8]) -> Result<()> {
self.file.write_all(bytes)
}
}
impl Drop for FileLock {
#[cfg(not(windows))]
fn drop(&mut self) {
if self.unlock().is_err() {
// This is wild; uh, oh
panic!("Failed to unlock file when dropping value");
}
}
#[cfg(windows)]
fn drop(&mut self) {
if !self.unlocked {
if self.unlock().is_err() {
// This is wild; uh, oh
panic!("Failed to unlock file when dropping value");
}
}
}
}
#[cfg(test)]

Loading…
Cancel
Save