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
use crate::{Error, ErrorKind};
use libc::{flock, EWOULDBLOCK, LOCK_EX, LOCK_NB, LOCK_UN};
use std::ops;
use std::os::unix::io::AsRawFd;
#[derive(Debug)]
pub struct FdLockGuard<'fdlock, T: AsRawFd> {
lock: &'fdlock mut FdLock<T>,
}
impl<T: AsRawFd> ops::Deref for FdLockGuard<'_, T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
&self.lock.t
}
}
impl<T: AsRawFd> ops::DerefMut for FdLockGuard<'_, T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.lock.t
}
}
impl<T: AsRawFd> Drop for FdLockGuard<'_, T> {
#[inline]
fn drop(&mut self) {
let fd = self.lock.t.as_raw_fd();
if unsafe { flock(fd, LOCK_UN | LOCK_NB) } != 0 {
panic!("Could not unlock the file descriptor");
}
}
}
#[derive(Debug)]
pub struct FdLock<T: AsRawFd> {
t: T,
}
impl<T: AsRawFd> FdLock<T> {
#[inline]
pub fn new(t: T) -> Self {
FdLock { t }
}
#[inline]
pub fn lock(&mut self) -> Result<FdLockGuard<'_, T>, Error> {
let fd = self.t.as_raw_fd();
match unsafe { flock(fd, LOCK_EX) } {
0 => Ok(FdLockGuard { lock: self }),
_ => Err(ErrorKind::Other.into()),
}
}
#[inline]
pub fn try_lock(&mut self) -> Result<FdLockGuard<'_, T>, Error> {
let fd = self.t.as_raw_fd();
match unsafe { flock(fd, LOCK_EX | LOCK_NB) } {
0 => Ok(FdLockGuard { lock: self }),
EWOULDBLOCK => Err(ErrorKind::Locked.into()),
_ => Err(ErrorKind::Other.into()),
}
}
}