Echo Writes Code

file_locking.rs

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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//! # Simple, Lightweight File Locking
//!
//! This crate provides an extremely lean implementation of file locking for POSIX
//! and Windows systems.
//!
//! The locking primitives used are `flock()` on POSIX (called through the
//! [`libc`](https://crates.io/crates/libc) crate), and `LockFileEx()` /
//! `UnlockFile()` on Windows (called through the
//! [`windows-sys`](https://crates.io/crates/windows-sys) crate).
//!
//! The API is exposed as a single extension trait for [`std::fs::File`] called
//! [`FileExt`]. Simply bring the trait into scope, and you can lock files to
//! your heart's content:
//!
//! ```
//! # use std::fs::{ self };
//! use std::fs::{ File };
//! use file_locking::{ FileExt };
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let f = File::options()
//!   .create(true)
//!   .write(true)
//!   .open("database.lock")?;
//!
//! {
//!   let _guard = f.lock_exclusive()?;
//!
//!   // ... do some stuff with the knowledge that nobody else can lock the file ...
//! }
//!
//! // the lock is now released and can be taken again by somebody else c:
//! # fs::remove_file("database.lock")?;
//! # Ok(())
//! # }
//! ```
//!
//! Some unavoidable behavior differences exist between platforms. To summarize:
//!
//! - Don't count on file locks to prevent read or write access to a file, but
//!   be prepared for them to.
//! - Don't lock the same on-disk file through the same [`File`](std::fs::File)
//!   object more than once.
//! - Don't count on file locks working through network shares (NFS, SMB, etc.)
//!
//! Detailed differences are documented on the [`FileExt`] trait.

pub mod errors;
pub mod file_ext;

#[cfg(unix)]
mod unix;

#[cfg(windows)]
mod windows;

pub use errors::{ Error, Result };
pub use file_ext::{ FileExt };

#[cfg(test)]
mod tests {
	use super::*;

	use std::fs::{ File, self };
	use std::path::{ Path, PathBuf };

	struct TestFile {
		path: PathBuf,
		file: File,
	}

	impl TestFile {
		fn new<P: AsRef<Path>>(path: P) -> Result<TestFile> {
			let path = path.as_ref();

			let file = File::options()
				.create_new(true)
				.write(true)
				.open(path)
				.expect("Should be able to create test file");

			Ok(TestFile {
				path: path.to_path_buf(),
				file,
			})
		}
	}

	impl Drop for TestFile {
		fn drop(&mut self) {
			let _ = fs::remove_file(&self.path);
		}
	}

	#[test]
	fn lock_shared_works() {
		const TEST_FILE_PATH: &str = "test_lock_shared.txt";
		let f = TestFile::new(TEST_FILE_PATH).expect("File should be created and opened");
		let _guard = f.file.lock_shared().expect("Shared file lock should be obtained");
	}

	#[test]
	fn lock_exclusive_works() {
		const TEST_FILE_PATH: &str = "test_lock_exclusive.txt";
		let f = TestFile::new(TEST_FILE_PATH).expect("File should be created and opened");
		let _guard = f.file.lock_exclusive().expect("Exclusive file lock should be obtained");
	}

	#[test]
	fn try_lock_shared_works() {
		const TEST_FILE_PATH: &str = "test_try_lock_shared.txt";
		let f = TestFile::new(TEST_FILE_PATH).expect("File should be created and opened");
		let _guard = f.file.try_lock_shared().expect("Shared file lock should be obtained");
	}

	#[test]
	fn try_lock_exclusive_works() {
		const TEST_FILE_PATH: &str = "test_try_lock_exclusive.txt";
		let f = TestFile::new(TEST_FILE_PATH).expect("File should be created and opened");
		let _guard = f.file.try_lock_shared().expect("Shared file lock should be obtained");
	}

	#[test]
	fn try_lock_shared_does_not_block() {
		const TEST_FILE_PATH: &str = "test_try_lock_shared_does_not_block.txt";
		let f = TestFile::new(TEST_FILE_PATH).expect("File should be created and opened");
		let _guard = f.file.lock_exclusive().expect("Exclusive file lock should be obtained");
		assert_shared_lock_fails(TEST_FILE_PATH);
	}

	#[test]
	fn try_lock_exclusive_does_not_block() {
		const TEST_FILE_PATH: &str = "test_try_lock_exclusive_does_not_block.txt";
		let f = TestFile::new(TEST_FILE_PATH).expect("File should be created and opened");
		let _guard = f.file.lock_exclusive().expect("Exclusive file lock should be obtained");
		assert_exclusive_lock_fails(TEST_FILE_PATH);
	}

	#[test]
	fn lock_guard_going_out_of_scope_releases_lock() {
		const TEST_FILE_PATH: &str = "test_lock_guard_going_out_of_scope_releases_lock.txt";
		let f = TestFile::new(TEST_FILE_PATH).expect("File should be created and opened");

		{
			let _guard = f.file.lock_exclusive().expect("Exclusive file lock should be obtained");
			assert_shared_lock_fails(TEST_FILE_PATH);
		}

		{
			let f2 = File::options()
				.read(true)
				.open(TEST_FILE_PATH)
				.expect("Second handle to the same file should be opened");

			let result = f2.try_lock_shared();
			let _ = result.expect("Shared lock should succeed");
		}

		{
			let f2 = File::options()
				.read(true)
				.open(TEST_FILE_PATH)
				.expect("Second handle to the same file should be opened");

			let result = f2.try_lock_exclusive();
			let _ = result.expect("Exclusive lock should succeed");
		}
	}

	fn assert_shared_lock_fails<P: AsRef<Path>>(path: P) {
		let f2 = File::options()
			.read(true)
			.open(path)
			.expect("Second handle to the same file should be opened");

		let result = f2.try_lock_shared();

		if result.expect_err("Second file lock should not be obtained") != Error::AlreadyLocked {
			panic!("Result of trying to obtain a second file lock should be Error::AlreadyLocked");
		}
	}

	fn assert_exclusive_lock_fails<P: AsRef<Path>>(path: P) {
		let f2 = File::options()
			.read(true)
			.open(path)
			.expect("Second handle to the same file should be opened");

		let result = f2.try_lock_exclusive();

		if result.expect_err("Second file lock should not be obtained") != Error::AlreadyLocked {
			panic!("Result of trying to obtain a second file lock should be Error::AlreadyLocked");
		}
	}
}