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
use libc::{flock, LOCK_EX, LOCK_NB, LOCK_UN};
use std::io::{self, Error, ErrorKind};
use std::ops;
use std::os::unix::io::AsRawFd;

/// A guard that unlocks the file descriptor when it goes out of scope.
///
/// # Panics
///
/// Dropping this type may panic if the lock fails to unlock.
#[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");
        }
    }
}

/// A file descriptor lock.
#[derive(Debug)]
pub struct FdLock<T: AsRawFd> {
    t: T,
}

impl<T: AsRawFd> FdLock<T> {
    /// Create a new instance.
    #[inline]
    pub fn new(t: T) -> Self {
        FdLock { t }
    }

    /// Acquires a new lock, blocking the current thread until it's able to do so.
    ///
    /// This function will block the local thread until it is available to acquire the lock. Upon
    /// returning, the thread is the only thread with the lock held. An RAII guard is returned to allow
    /// scoped unlock of the lock. When the guard goes out of scope, the lock will be unlocked.
    ///
    /// # Errors
    ///
    /// On Unix this may return an error if the operation was interrupted by a signal handler.
    #[inline]
    pub fn lock(&mut self) -> io::Result<FdLockGuard<'_, T>> {
        let fd = self.t.as_raw_fd();
        match unsafe { flock(fd, LOCK_EX) } {
            0 => Ok(FdLockGuard { lock: self }),
            _ => Err(Error::last_os_error()),
        }
    }

    /// Attempts to acquire an advisory lock.
    ///
    /// Unlike `FdLock::lock` this function will never block, but instead will
    /// return an error if the lock cannot be acquired.
    ///
    /// # Errors
    ///
    /// If the lock is already held and `ErrorKind::WouldBlock` error is
    /// returned. This may also return an error if the operation was interrupted
    /// by a signal handler.
    #[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 }),
            _ => match Error::last_os_error().kind() {
                ErrorKind::AlreadyExists | ErrorKind::WouldBlock => {
                    Err(ErrorKind::WouldBlock.into())
                }
                kind => Err(kind.into()),
            },
        }
    }
}