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
use std::io::{self, Error, ErrorKind};
use std::mem;
use std::ops;
use std::os::windows::io::AsRawHandle;
use winapi::um::fileapi::{LockFile, LockFileEx, UnlockFile};
use winapi::um::minwinbase::{LOCKFILE_EXCLUSIVE_LOCK, OVERLAPPED};
#[derive(Debug)]
pub struct FdLockGuard<'fdlock, T: AsRawHandle> {
lock: &'fdlock mut FdLock<T>,
}
impl<T: AsRawHandle> ops::Deref for FdLockGuard<'_, T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
&self.lock.t
}
}
impl<T: AsRawHandle> ops::DerefMut for FdLockGuard<'_, T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.lock.t
}
}
impl<T: AsRawHandle> Drop for FdLockGuard<'_, T> {
#[inline]
fn drop(&mut self) {
let handle = self.lock.t.as_raw_handle();
if unsafe { !UnlockFile(handle, 0, 0, 1, 0) } == 0 {
panic!("Could not unlock the file descriptor");
}
}
}
#[derive(Debug)]
pub struct FdLock<T: AsRawHandle> {
t: T,
}
impl<T: AsRawHandle> FdLock<T> {
#[inline]
pub fn new(t: T) -> Self {
FdLock { t }
}
#[inline]
pub fn lock(&mut self) -> Result<FdLockGuard<'_, T>, Error> {
let handle = self.t.as_raw_handle();
let overlapped = Overlapped::zero();
let flags = LOCKFILE_EXCLUSIVE_LOCK;
match unsafe { LockFileEx(handle, flags, 0, 1, 0, overlapped.raw()) } {
0 => Err(ErrorKind::Other.into()),
_ => Ok(FdLockGuard { lock: self }),
}
}
#[inline]
pub fn try_lock(&mut self) -> io::Result<FdLockGuard<'_, T>> {
let handle = self.t.as_raw_handle();
match unsafe { LockFile(handle, 0, 0, 1, 0) } {
1 => Ok(FdLockGuard { lock: self }),
_ => {
let err = Error::last_os_error();
Err(Error::new(ErrorKind::WouldBlock, format!("{}", err)))
}
}
}
}
struct Overlapped(OVERLAPPED);
impl Overlapped {
fn zero() -> Overlapped {
Overlapped(unsafe { mem::zeroed() })
}
fn raw(&self) -> *mut OVERLAPPED {
&self.0 as *const _ as *mut _
}
}