ddb_core/file_io/
locking.rs1use crate::error::{DdbError, Result};
3use fs2::FileExt;
4use std::fs::File;
5use std::path::{Path, PathBuf};
6
7pub struct FileLock {
8 file: File,
9 _path: PathBuf,
10}
11
12impl FileLock {
13 pub fn new<P: AsRef<Path>>(path: P) -> Result<Self> {
14 let path = path.as_ref().to_path_buf();
15 let file = File::open(&path)
16 .map_err(|e| DdbError::LockError(format!("Failed to open file: {}", e)))?;
17
18 Ok(Self { file, _path: path })
19 }
20
21 pub fn lock_shared(&self) -> Result<()> {
22 self.file
23 .lock_shared()
24 .map_err(|e| DdbError::LockError(format!("Failed to acquire shared lock: {}", e)))
25 }
26
27 pub fn lock_exclusive(&self) -> Result<()> {
28 self.file
29 .lock_exclusive()
30 .map_err(|e| DdbError::LockError(format!("Failed to acquire exclusive lock: {}", e)))
31 }
32
33 pub fn unlock(&self) -> Result<()> {
34 self.file
35 .unlock()
36 .map_err(|e| DdbError::LockError(format!("Failed to unlock: {}", e)))
37 }
38}
39
40impl Drop for FileLock {
41 fn drop(&mut self) {
42 let _ = self.unlock();
43 }
44}