use std::{
fs, io,
path::{Path, PathBuf},
};
use crate::DbError;
const LOCK_FILE: &str = "store.lock";
pub(crate) struct WriterLock {
path: PathBuf,
}
impl WriterLock {
pub(crate) fn acquire(root: &Path) -> Result<Self, DbError> {
let path = root.join(LOCK_FILE);
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(_file) => Ok(Self { path }),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
Err(DbError::WriterLockHeld)
}
Err(error) => Err(DbError::io("acquire writer lock", error)),
}
}
}
impl Drop for WriterLock {
fn drop(&mut self) {
let _result = fs::remove_file(&self.path);
}
}