Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 2744f79

Browse files
committedOct 13, 2024·
Implement file_lock feature
This adds lock(), lock_shared(), try_lock(), try_lock_shared(), and unlock() to File gated behind the file_lock feature flag
1 parent a1fd235 commit 2744f79

File tree

10 files changed

+507
-0
lines changed

10 files changed

+507
-0
lines changed
 

‎library/std/src/fs.rs

Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -615,6 +615,223 @@ impl File {
615615
self.inner.datasync()
616616
}
617617

618+
/// Acquire an exclusive advisory lock on the file. Blocks until the lock can be acquired.
619+
///
620+
/// This acquires an exclusive advisory lock; no other file handle to this file may acquire
621+
/// another lock.
622+
///
623+
/// If this file handle, or a clone of it, already holds an advisory lock the exact behavior is
624+
/// unspecified and platform dependent, including the possibility that it will deadlock.
625+
/// However, if this method returns, then an exclusive lock is held.
626+
///
627+
/// If the file not open for writing, it is unspecified whether this function returns an error.
628+
///
629+
/// Note, this is an advisory lock meant to interact with [`lock_shared`], [`try_lock`],
630+
/// [`try_lock_shared`], and [`unlock`]. Its interactions with other methods, such as [`read`]
631+
/// and [`write`] are platform specific, and it may or may not cause non-lockholders to block.
632+
///
633+
/// # Platform-specific behavior
634+
///
635+
/// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` flag,
636+
/// and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK` flag. Note that,
637+
/// this [may change in the future][changes].
638+
///
639+
/// [changes]: io#platform-specific-behavior
640+
///
641+
/// [`lock_shared`]: File::lock_shared
642+
/// [`try_lock`]: File::try_lock
643+
/// [`try_lock_shared`]: File::try_lock_shared
644+
/// [`unlock`]: File::unlock
645+
/// [`read`]: Read::read
646+
/// [`write`]: Write::write
647+
///
648+
/// # Examples
649+
///
650+
/// ```no_run
651+
/// #![feature(file_lock)]
652+
/// use std::fs::File;
653+
///
654+
/// fn main() -> std::io::Result<()> {
655+
/// let f = File::open("foo.txt")?;
656+
/// f.lock()?;
657+
/// Ok(())
658+
/// }
659+
/// ```
660+
#[unstable(feature = "file_lock", issue = "130994")]
661+
pub fn lock(&self) -> io::Result<()> {
662+
self.inner.lock()
663+
}
664+
665+
/// Acquire a shared advisory lock on the file. Blocks until the lock can be acquired.
666+
///
667+
/// This acquires a shared advisory lock; more than one file handle may hold a shared lock, but
668+
/// none may hold an exclusive lock.
669+
///
670+
/// If this file handle, or a clone of it, already holds an advisory lock, the exact behavior is
671+
/// unspecified and platform dependent, including the possibility that it will deadlock.
672+
/// However, if this method returns, then a shared lock is held.
673+
///
674+
/// Note, this is an advisory lock meant to interact with [`lock`], [`try_lock`],
675+
/// [`try_lock_shared`], and [`unlock`]. Its interactions with other methods, such as [`read`]
676+
/// and [`write`] are platform specific, and it may or may not cause non-lockholders to block.
677+
///
678+
/// # Platform-specific behavior
679+
///
680+
/// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` flag,
681+
/// and the `LockFileEx` function on Windows. Note that, this
682+
/// [may change in the future][changes].
683+
///
684+
/// [changes]: io#platform-specific-behavior
685+
///
686+
/// [`lock`]: File::lock
687+
/// [`try_lock`]: File::try_lock
688+
/// [`try_lock_shared`]: File::try_lock_shared
689+
/// [`unlock`]: File::unlock
690+
/// [`read`]: Read::read
691+
/// [`write`]: Write::write
692+
///
693+
/// # Examples
694+
///
695+
/// ```no_run
696+
/// #![feature(file_lock)]
697+
/// use std::fs::File;
698+
///
699+
/// fn main() -> std::io::Result<()> {
700+
/// let f = File::open("foo.txt")?;
701+
/// f.lock_shared()?;
702+
/// Ok(())
703+
/// }
704+
/// ```
705+
#[unstable(feature = "file_lock", issue = "130994")]
706+
pub fn lock_shared(&self) -> io::Result<()> {
707+
self.inner.lock_shared()
708+
}
709+
710+
/// Acquire an exclusive advisory lock on the file. Returns `Ok(false)` if the file is locked.
711+
///
712+
/// This acquires an exclusive advisory lock; no other file handle to this file may acquire
713+
/// another lock.
714+
///
715+
/// If this file handle, or a clone of it, already holds an advisory lock, the exact behavior is
716+
/// unspecified and platform dependent, including the possibility that it will deadlock.
717+
/// However, if this method returns, then an exclusive lock is held.
718+
///
719+
/// If the file not open for writing, it is unspecified whether this function returns an error.
720+
///
721+
/// Note, this is an advisory lock meant to interact with [`lock`], [`lock_shared`],
722+
/// [`try_lock_shared`], and [`unlock`]. Its interactions with other methods, such as [`read`]
723+
/// and [`write`] are platform specific, and it may or may not cause non-lockholders to block.
724+
///
725+
/// # Platform-specific behavior
726+
///
727+
/// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` and
728+
/// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK`
729+
/// and `LOCKFILE_FAIL_IMMEDIATELY` flags. Note that, this
730+
/// [may change in the future][changes].
731+
///
732+
/// [changes]: io#platform-specific-behavior
733+
///
734+
/// [`lock`]: File::lock
735+
/// [`lock_shared`]: File::lock_shared
736+
/// [`try_lock_shared`]: File::try_lock_shared
737+
/// [`unlock`]: File::unlock
738+
/// [`read`]: Read::read
739+
/// [`write`]: Write::write
740+
///
741+
/// # Examples
742+
///
743+
/// ```no_run
744+
/// #![feature(file_lock)]
745+
/// use std::fs::File;
746+
///
747+
/// fn main() -> std::io::Result<()> {
748+
/// let f = File::open("foo.txt")?;
749+
/// f.try_lock()?;
750+
/// Ok(())
751+
/// }
752+
/// ```
753+
#[unstable(feature = "file_lock", issue = "130994")]
754+
pub fn try_lock(&self) -> io::Result<bool> {
755+
self.inner.try_lock()
756+
}
757+
758+
/// Acquire a shared advisory lock on the file.
759+
/// Returns `Ok(false)` if the file is exclusively locked.
760+
///
761+
/// This acquires a shared advisory lock; more than one file handle may hold a shared lock, but
762+
/// none may hold an exclusive lock.
763+
///
764+
/// If this file handle, or a clone of it, already holds an advisory lock, the exact behavior is
765+
/// unspecified and platform dependent, including the possibility that it will deadlock.
766+
/// However, if this method returns, then a shared lock is held.
767+
///
768+
/// Note, this is an advisory lock meant to interact with [`lock`], [`try_lock`],
769+
/// [`try_lock`], and [`unlock`]. Its interactions with other methods, such as [`read`]
770+
/// and [`write`] are platform specific, and it may or may not cause non-lockholders to block.
771+
///
772+
/// # Platform-specific behavior
773+
///
774+
/// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` and
775+
/// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the
776+
/// `LOCKFILE_FAIL_IMMEDIATELY` flag. Note that, this
777+
/// [may change in the future][changes].
778+
///
779+
/// [changes]: io#platform-specific-behavior
780+
///
781+
/// [`lock`]: File::lock
782+
/// [`lock_shared`]: File::lock_shared
783+
/// [`try_lock`]: File::try_lock
784+
/// [`unlock`]: File::unlock
785+
/// [`read`]: Read::read
786+
/// [`write`]: Write::write
787+
///
788+
/// # Examples
789+
///
790+
/// ```no_run
791+
/// #![feature(file_lock)]
792+
/// use std::fs::File;
793+
///
794+
/// fn main() -> std::io::Result<()> {
795+
/// let f = File::open("foo.txt")?;
796+
/// f.try_lock_shared()?;
797+
/// Ok(())
798+
/// }
799+
/// ```
800+
#[unstable(feature = "file_lock", issue = "130994")]
801+
pub fn try_lock_shared(&self) -> io::Result<bool> {
802+
self.inner.try_lock_shared()
803+
}
804+
805+
/// Release all locks on the file.
806+
///
807+
/// All remaining locks are released when the file handle, and all clones of it, are dropped.
808+
///
809+
/// # Platform-specific behavior
810+
///
811+
/// This function currently corresponds to the `flock` function on Unix with the `LOCK_UN` flag,
812+
/// and the `UnlockFile` function on Windows. Note that, this
813+
/// [may change in the future][changes].
814+
///
815+
/// [changes]: io#platform-specific-behavior
816+
///
817+
/// # Examples
818+
///
819+
/// ```no_run
820+
/// #![feature(file_lock)]
821+
/// use std::fs::File;
822+
///
823+
/// fn main() -> std::io::Result<()> {
824+
/// let f = File::open("foo.txt")?;
825+
/// f.lock()?;
826+
/// f.unlock()?;
827+
/// Ok(())
828+
/// }
829+
/// ```
830+
#[unstable(feature = "file_lock", issue = "130994")]
831+
pub fn unlock(&self) -> io::Result<()> {
832+
self.inner.unlock()
833+
}
834+
618835
/// Truncates or extends the underlying file, updating the size of
619836
/// this file to become `size`.
620837
///

‎library/std/src/fs/tests.rs

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,86 @@ fn file_test_io_seek_and_write() {
203203
assert!(read_str == final_msg);
204204
}
205205

206+
#[test]
207+
fn file_lock_multiple_shared() {
208+
let tmpdir = tmpdir();
209+
let filename = &tmpdir.join("file_lock_multiple_shared_test.txt");
210+
let f1 = check!(File::create(filename));
211+
let f2 = check!(OpenOptions::new().write(true).open(filename));
212+
213+
// Check that we can acquire concurrent shared locks
214+
check!(f1.lock_shared());
215+
check!(f2.lock_shared());
216+
check!(f1.unlock());
217+
check!(f2.unlock());
218+
assert!(check!(f1.try_lock_shared()));
219+
assert!(check!(f2.try_lock_shared()));
220+
}
221+
222+
#[test]
223+
fn file_lock_blocking() {
224+
let tmpdir = tmpdir();
225+
let filename = &tmpdir.join("file_lock_blocking_test.txt");
226+
let f1 = check!(File::create(filename));
227+
let f2 = check!(OpenOptions::new().write(true).open(filename));
228+
229+
// Check that shared locks block exclusive locks
230+
check!(f1.lock_shared());
231+
assert!(!check!(f2.try_lock()));
232+
check!(f1.unlock());
233+
234+
// Check that exclusive locks block shared locks
235+
check!(f1.lock());
236+
assert!(!check!(f2.try_lock_shared()));
237+
}
238+
239+
#[test]
240+
fn file_lock_drop() {
241+
let tmpdir = tmpdir();
242+
let filename = &tmpdir.join("file_lock_dup_test.txt");
243+
let f1 = check!(File::create(filename));
244+
let f2 = check!(OpenOptions::new().write(true).open(filename));
245+
246+
// Check that locks are released when the File is dropped
247+
check!(f1.lock_shared());
248+
assert!(!check!(f2.try_lock()));
249+
drop(f1);
250+
assert!(check!(f2.try_lock()));
251+
}
252+
253+
#[test]
254+
fn file_lock_dup() {
255+
let tmpdir = tmpdir();
256+
let filename = &tmpdir.join("file_lock_dup_test.txt");
257+
let f1 = check!(File::create(filename));
258+
let f2 = check!(OpenOptions::new().write(true).open(filename));
259+
260+
// Check that locks are not dropped if the File has been cloned
261+
check!(f1.lock_shared());
262+
assert!(!check!(f2.try_lock()));
263+
let cloned = check!(f1.try_clone());
264+
drop(f1);
265+
assert!(!check!(f2.try_lock()));
266+
drop(cloned)
267+
}
268+
269+
#[test]
270+
#[cfg(windows)]
271+
fn file_lock_double_unlock() {
272+
let tmpdir = tmpdir();
273+
let filename = &tmpdir.join("file_lock_double_unlock_test.txt");
274+
let f1 = check!(File::create(filename));
275+
let f2 = check!(OpenOptions::new().write(true).open(filename));
276+
277+
// On Windows a file handle may acquire both a shared and exclusive lock.
278+
// Check that both are released by unlock()
279+
check!(f1.lock());
280+
check!(f1.lock_shared());
281+
assert!(!check!(f2.try_lock()));
282+
check!(f1.unlock());
283+
assert!(check!(f2.try_lock()));
284+
}
285+
206286
#[test]
207287
fn file_test_io_seek_shakedown() {
208288
// 01234567890123

‎library/std/src/sys/pal/hermit/fs.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,26 @@ impl File {
364364
self.fsync()
365365
}
366366

367+
pub fn lock(&self) -> io::Result<()> {
368+
unsupported()
369+
}
370+
371+
pub fn lock_shared(&self) -> io::Result<()> {
372+
unsupported()
373+
}
374+
375+
pub fn try_lock(&self) -> io::Result<bool> {
376+
unsupported()
377+
}
378+
379+
pub fn try_lock_shared(&self) -> io::Result<bool> {
380+
unsupported()
381+
}
382+
383+
pub fn unlock(&self) -> io::Result<()> {
384+
unsupported()
385+
}
386+
367387
pub fn truncate(&self, _size: u64) -> io::Result<()> {
368388
Err(Error::from_raw_os_error(22))
369389
}

‎library/std/src/sys/pal/solid/fs.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,26 @@ impl File {
350350
self.flush()
351351
}
352352

353+
pub fn lock(&self) -> io::Result<()> {
354+
unsupported()
355+
}
356+
357+
pub fn lock_shared(&self) -> io::Result<()> {
358+
unsupported()
359+
}
360+
361+
pub fn try_lock(&self) -> io::Result<bool> {
362+
unsupported()
363+
}
364+
365+
pub fn try_lock_shared(&self) -> io::Result<bool> {
366+
unsupported()
367+
}
368+
369+
pub fn unlock(&self) -> io::Result<()> {
370+
unsupported()
371+
}
372+
353373
pub fn truncate(&self, _size: u64) -> io::Result<()> {
354374
unsupported()
355375
}

‎library/std/src/sys/pal/unix/fs.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1254,6 +1254,43 @@ impl File {
12541254
}
12551255
}
12561256

1257+
pub fn lock(&self) -> io::Result<()> {
1258+
cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX) })?;
1259+
return Ok(());
1260+
}
1261+
1262+
pub fn lock_shared(&self) -> io::Result<()> {
1263+
cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH) })?;
1264+
return Ok(());
1265+
}
1266+
1267+
pub fn try_lock(&self) -> io::Result<bool> {
1268+
let result = cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) });
1269+
if let Err(ref err) = result {
1270+
if err.kind() == io::ErrorKind::WouldBlock {
1271+
return Ok(false);
1272+
}
1273+
}
1274+
result?;
1275+
return Ok(true);
1276+
}
1277+
1278+
pub fn try_lock_shared(&self) -> io::Result<bool> {
1279+
let result = cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) });
1280+
if let Err(ref err) = result {
1281+
if err.kind() == io::ErrorKind::WouldBlock {
1282+
return Ok(false);
1283+
}
1284+
}
1285+
result?;
1286+
return Ok(true);
1287+
}
1288+
1289+
pub fn unlock(&self) -> io::Result<()> {
1290+
cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_UN) })?;
1291+
return Ok(());
1292+
}
1293+
12571294
pub fn truncate(&self, size: u64) -> io::Result<()> {
12581295
let size: off64_t =
12591296
size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;

‎library/std/src/sys/pal/unsupported/fs.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,26 @@ impl File {
198198
self.0
199199
}
200200

201+
pub fn lock(&self) -> io::Result<()> {
202+
self.0
203+
}
204+
205+
pub fn lock_shared(&self) -> io::Result<()> {
206+
self.0
207+
}
208+
209+
pub fn try_lock(&self) -> io::Result<bool> {
210+
self.0
211+
}
212+
213+
pub fn try_lock_shared(&self) -> io::Result<bool> {
214+
self.0
215+
}
216+
217+
pub fn unlock(&self) -> io::Result<()> {
218+
self.0
219+
}
220+
201221
pub fn truncate(&self, _size: u64) -> io::Result<()> {
202222
self.0
203223
}

‎library/std/src/sys/pal/wasi/fs.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,26 @@ impl File {
420420
self.fd.datasync()
421421
}
422422

423+
pub fn lock(&self) -> io::Result<()> {
424+
unsupported()
425+
}
426+
427+
pub fn lock_shared(&self) -> io::Result<()> {
428+
unsupported()
429+
}
430+
431+
pub fn try_lock(&self) -> io::Result<bool> {
432+
unsupported()
433+
}
434+
435+
pub fn try_lock_shared(&self) -> io::Result<bool> {
436+
unsupported()
437+
}
438+
439+
pub fn unlock(&self) -> io::Result<()> {
440+
unsupported()
441+
}
442+
423443
pub fn truncate(&self, size: u64) -> io::Result<()> {
424444
self.fd.filestat_set_size(size)
425445
}

‎library/std/src/sys/pal/windows/c/bindings.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2349,6 +2349,9 @@ Windows.Win32.Storage.FileSystem.GetFinalPathNameByHandleW
23492349
Windows.Win32.Storage.FileSystem.GetFullPathNameW
23502350
Windows.Win32.Storage.FileSystem.GetTempPathW
23512351
Windows.Win32.Storage.FileSystem.INVALID_FILE_ATTRIBUTES
2352+
Windows.Win32.Storage.FileSystem.LOCKFILE_EXCLUSIVE_LOCK
2353+
Windows.Win32.Storage.FileSystem.LOCKFILE_FAIL_IMMEDIATELY
2354+
Windows.Win32.Storage.FileSystem.LockFileEx
23522355
Windows.Win32.Storage.FileSystem.LPPROGRESS_ROUTINE
23532356
Windows.Win32.Storage.FileSystem.LPPROGRESS_ROUTINE_CALLBACK_REASON
23542357
Windows.Win32.Storage.FileSystem.MAXIMUM_REPARSE_DATA_BUFFER_SIZE
@@ -2394,6 +2397,7 @@ Windows.Win32.Storage.FileSystem.SYMBOLIC_LINK_FLAG_DIRECTORY
23942397
Windows.Win32.Storage.FileSystem.SYMBOLIC_LINK_FLAGS
23952398
Windows.Win32.Storage.FileSystem.SYNCHRONIZE
23962399
Windows.Win32.Storage.FileSystem.TRUNCATE_EXISTING
2400+
Windows.Win32.Storage.FileSystem.UnlockFile
23972401
Windows.Win32.Storage.FileSystem.VOLUME_NAME_DOS
23982402
Windows.Win32.Storage.FileSystem.VOLUME_NAME_GUID
23992403
Windows.Win32.Storage.FileSystem.VOLUME_NAME_NONE

‎library/std/src/sys/pal/windows/c/windows_sys.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ windows_targets::link!("kernel32.dll" "system" fn InitOnceBeginInitialize(lpinit
6565
windows_targets::link!("kernel32.dll" "system" fn InitOnceComplete(lpinitonce : *mut INIT_ONCE, dwflags : u32, lpcontext : *const core::ffi::c_void) -> BOOL);
6666
windows_targets::link!("kernel32.dll" "system" fn InitializeProcThreadAttributeList(lpattributelist : LPPROC_THREAD_ATTRIBUTE_LIST, dwattributecount : u32, dwflags : u32, lpsize : *mut usize) -> BOOL);
6767
windows_targets::link!("kernel32.dll" "system" fn LocalFree(hmem : HLOCAL) -> HLOCAL);
68+
windows_targets::link!("kernel32.dll" "system" fn LockFileEx(hfile : HANDLE, dwflags : LOCK_FILE_FLAGS, dwreserved : u32, nnumberofbytestolocklow : u32, nnumberofbytestolockhigh : u32, lpoverlapped : *mut OVERLAPPED) -> BOOL);
6869
windows_targets::link!("kernel32.dll" "system" fn MoveFileExW(lpexistingfilename : PCWSTR, lpnewfilename : PCWSTR, dwflags : MOVE_FILE_FLAGS) -> BOOL);
6970
windows_targets::link!("kernel32.dll" "system" fn MultiByteToWideChar(codepage : u32, dwflags : MULTI_BYTE_TO_WIDE_CHAR_FLAGS, lpmultibytestr : PCSTR, cbmultibyte : i32, lpwidecharstr : PWSTR, cchwidechar : i32) -> i32);
7071
windows_targets::link!("kernel32.dll" "system" fn QueryPerformanceCounter(lpperformancecount : *mut i64) -> BOOL);
@@ -96,6 +97,7 @@ windows_targets::link!("kernel32.dll" "system" fn TlsGetValue(dwtlsindex : u32)
9697
windows_targets::link!("kernel32.dll" "system" fn TlsSetValue(dwtlsindex : u32, lptlsvalue : *const core::ffi::c_void) -> BOOL);
9798
windows_targets::link!("kernel32.dll" "system" fn TryAcquireSRWLockExclusive(srwlock : *mut SRWLOCK) -> BOOLEAN);
9899
windows_targets::link!("kernel32.dll" "system" fn TryAcquireSRWLockShared(srwlock : *mut SRWLOCK) -> BOOLEAN);
100+
windows_targets::link!("kernel32.dll" "system" fn UnlockFile(hfile : HANDLE, dwfileoffsetlow : u32, dwfileoffsethigh : u32, nnumberofbytestounlocklow : u32, nnumberofbytestounlockhigh : u32) -> BOOL);
99101
windows_targets::link!("kernel32.dll" "system" fn UpdateProcThreadAttribute(lpattributelist : LPPROC_THREAD_ATTRIBUTE_LIST, dwflags : u32, attribute : usize, lpvalue : *const core::ffi::c_void, cbsize : usize, lppreviousvalue : *mut core::ffi::c_void, lpreturnsize : *const usize) -> BOOL);
100102
windows_targets::link!("kernel32.dll" "system" fn WaitForMultipleObjects(ncount : u32, lphandles : *const HANDLE, bwaitall : BOOL, dwmilliseconds : u32) -> WAIT_EVENT);
101103
windows_targets::link!("kernel32.dll" "system" fn WaitForSingleObject(hhandle : HANDLE, dwmilliseconds : u32) -> WAIT_EVENT);
@@ -2725,6 +2727,9 @@ pub struct LINGER {
27252727
pub l_onoff: u16,
27262728
pub l_linger: u16,
27272729
}
2730+
pub const LOCKFILE_EXCLUSIVE_LOCK: LOCK_FILE_FLAGS = 2u32;
2731+
pub const LOCKFILE_FAIL_IMMEDIATELY: LOCK_FILE_FLAGS = 1u32;
2732+
pub type LOCK_FILE_FLAGS = u32;
27282733
pub type LPOVERLAPPED_COMPLETION_ROUTINE = Option<
27292734
unsafe extern "system" fn(
27302735
dwerrorcode: u32,

‎library/std/src/sys/pal/windows/fs.rs

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,90 @@ impl File {
346346
self.fsync()
347347
}
348348

349+
pub fn lock(&self) -> io::Result<()> {
350+
cvt(unsafe {
351+
let mut overlapped = mem::zeroed();
352+
c::LockFileEx(
353+
self.handle.as_raw_handle(),
354+
c::LOCKFILE_EXCLUSIVE_LOCK,
355+
0,
356+
u32::MAX,
357+
u32::MAX,
358+
&mut overlapped,
359+
)
360+
})?;
361+
Ok(())
362+
}
363+
364+
pub fn lock_shared(&self) -> io::Result<()> {
365+
cvt(unsafe {
366+
let mut overlapped = mem::zeroed();
367+
c::LockFileEx(self.handle.as_raw_handle(), 0, 0, u32::MAX, u32::MAX, &mut overlapped)
368+
})?;
369+
Ok(())
370+
}
371+
372+
pub fn try_lock(&self) -> io::Result<bool> {
373+
let result = cvt(unsafe {
374+
let mut overlapped = mem::zeroed();
375+
c::LockFileEx(
376+
self.handle.as_raw_handle(),
377+
c::LOCKFILE_EXCLUSIVE_LOCK | c::LOCKFILE_FAIL_IMMEDIATELY,
378+
0,
379+
u32::MAX,
380+
u32::MAX,
381+
&mut overlapped,
382+
)
383+
});
384+
385+
if let Err(ref err) = result {
386+
if err.raw_os_error() == Some(c::ERROR_IO_PENDING as i32) {
387+
return Ok(false);
388+
}
389+
}
390+
result?;
391+
Ok(true)
392+
}
393+
394+
pub fn try_lock_shared(&self) -> io::Result<bool> {
395+
let result = cvt(unsafe {
396+
let mut overlapped = mem::zeroed();
397+
c::LockFileEx(
398+
self.handle.as_raw_handle(),
399+
c::LOCKFILE_FAIL_IMMEDIATELY,
400+
0,
401+
u32::MAX,
402+
u32::MAX,
403+
&mut overlapped,
404+
)
405+
});
406+
407+
if let Err(ref err) = result {
408+
if err.raw_os_error() == Some(c::ERROR_IO_PENDING as i32) {
409+
return Ok(false);
410+
}
411+
}
412+
result?;
413+
Ok(true)
414+
}
415+
416+
pub fn unlock(&self) -> io::Result<()> {
417+
// Unlock the handle twice because LockFileEx() allows a file handle to acquire
418+
// both an exclusive and shared lock, in which case the documentation states that:
419+
// "...two unlock operations are necessary to unlock the region; the first unlock operation
420+
// unlocks the exclusive lock, the second unlock operation unlocks the shared lock"
421+
cvt(unsafe { c::UnlockFile(self.handle.as_raw_handle(), 0, 0, u32::MAX, u32::MAX) })?;
422+
let result =
423+
cvt(unsafe { c::UnlockFile(self.handle.as_raw_handle(), 0, 0, u32::MAX, u32::MAX) });
424+
if let Err(ref err) = result {
425+
if err.raw_os_error() == Some(c::ERROR_NOT_LOCKED as i32) {
426+
return Ok(());
427+
}
428+
}
429+
result?;
430+
Ok(())
431+
}
432+
349433
pub fn truncate(&self, size: u64) -> io::Result<()> {
350434
let info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as i64 };
351435
api::set_file_information_by_handle(self.handle.as_raw_handle(), &info).io_result()

0 commit comments

Comments
 (0)
Please sign in to comment.