1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use std::fs::{remove_file, File, OpenOptions};
use std::io::{Read, Result, Seek, Write};
use std::ops::{Deref, DerefMut, Drop};
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct LockedFile {
file: File,
path: PathBuf,
lock_file_path: PathBuf,
}
impl LockedFile {
pub fn open_read_write<T: AsRef<Path>>(path: T) -> Result<Option<LockedFile>> {
let path = path.as_ref().to_path_buf();
let extension = if let Some(ext) = path.extension() {
let mut ext = String::from(ext.to_string_lossy());
ext.push_str(".lock");
ext
} else {
"lock".to_string()
};
let lock_file_path = path.with_extension(extension);
if Path::exists(&lock_file_path) {
Ok(None)
} else {
OpenOptions::new()
.create(true)
.write(true)
.open(&lock_file_path)?;
let file = OpenOptions::new()
.create(true)
.read(true)
.write(true)
.open(&path)?;
Ok(Some(LockedFile {
file,
path,
lock_file_path,
}))
}
}
}
impl Deref for LockedFile {
type Target = File;
fn deref(&self) -> &File {
&self.file
}
}
impl DerefMut for LockedFile {
fn deref_mut(&mut self) -> &mut File {
&mut self.file
}
}
impl Drop for LockedFile {
fn drop(&mut self) {
if self.lock_file_path.exists() {
remove_file(&self.lock_file_path).unwrap_or_else(|_| {
panic!(
"Unable to delete lock file for {:?}, something went wrong",
self.path
)
});
}
}
}
impl Read for LockedFile {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.file.read(buf)
}
}
impl Write for LockedFile {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.file.write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
self.file.flush()
}
}
impl Seek for LockedFile {
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
self.file.seek(pos)
}
}