Echo Writes Code

windows.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
use crate::errors::{ Error, Result };
use crate::file_ext::{ FileExt };

use errno::{ Errno, errno };
use windows_sys::Win32::Foundation::{ ERROR_LOCK_VIOLATION };
use windows_sys::Win32::Storage::FileSystem::{ LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx, UnlockFile };
use windows_sys::Win32::System::IO::{ OVERLAPPED };

use std::fs::{ File };
use std::mem::{ self };
use std::os::windows::io::{ AsHandle, AsRawHandle, BorrowedHandle };

impl FileExt for File {
	type LockGuard<'a> = LockGuard<'a>;

	fn lock_shared(&self) -> Result<Self::LockGuard<'_>> {
		lock(self.as_handle(), 0)
	}

	fn lock_exclusive(&self) -> Result<Self::LockGuard<'_>> {
		lock(self.as_handle(), LOCKFILE_EXCLUSIVE_LOCK)
	}

	fn try_lock_shared(&self) -> Result<Self::LockGuard<'_>> {
		try_lock(self.as_handle(), 0)
	}

	fn try_lock_exclusive(&self) -> Result<Self::LockGuard<'_>> {
		try_lock(self.as_handle(), LOCKFILE_EXCLUSIVE_LOCK)
	}
}

#[derive(Debug)]
#[must_use = "Not retaining the guard object will result in the file being immediately unlocked"]
pub struct LockGuard<'a> {
	handle: BorrowedHandle<'a>,
}

impl Drop for LockGuard<'_> {
	fn drop(&mut self) {
		unsafe {
			UnlockFile(self.handle.as_raw_handle(), LOCK_OFFSET_LO, LOCK_OFFSET_HI, LOCK_LENGTH_LO, LOCK_LENGTH_HI);
		}
	}
}

fn lock(handle: BorrowedHandle, flags: u32) -> Result<LockGuard> {
	let status = unsafe {
		const RESERVED: u32 = 0;

		let mut overlapped = mem::zeroed::<OVERLAPPED>();
		overlapped.Anonymous.Anonymous.Offset = LOCK_OFFSET_LO;
		overlapped.Anonymous.Anonymous.OffsetHigh = LOCK_OFFSET_HI;

		LockFileEx(handle.as_raw_handle(), flags, RESERVED, LOCK_LENGTH_LO, LOCK_LENGTH_HI, &mut overlapped as *mut OVERLAPPED)
	};

	match status {
		0 => Err(Error::LockFailed(errno())),
		_ => Ok(LockGuard { handle }),
	}
}

fn try_lock(handle: BorrowedHandle, flags: u32) -> Result<LockGuard> {
	let status = unsafe {
		const RESERVED: u32 = 0;

		let mut overlapped = mem::zeroed::<OVERLAPPED>();
		overlapped.Anonymous.Anonymous.Offset = LOCK_OFFSET_LO;
		overlapped.Anonymous.Anonymous.OffsetHigh = LOCK_OFFSET_HI;

		LockFileEx(handle.as_raw_handle(), flags | LOCKFILE_FAIL_IMMEDIATELY, RESERVED, LOCK_LENGTH_LO, LOCK_LENGTH_HI, &mut overlapped as *mut OVERLAPPED)
	};

	match status {
		0 => {
			let e = errno();

			if e == Errno(ERROR_LOCK_VIOLATION as i32) {
				Err(Error::AlreadyLocked)
			} else {
				Err(Error::LockFailed(e))
			}
		},
		_ => Ok(LockGuard { handle }),
	}
}

const LOCK_OFFSET_LO: u32 = 0;
const LOCK_OFFSET_HI: u32 = 0;
const LOCK_LENGTH_LO: u32 = !0;
const LOCK_LENGTH_HI: u32 = !0;