]> git.proxmox.com Git - proxmox.git/commitdiff
tools: fd: improve drop handler and add some helpers
authorWolfgang Bumiller <w.bumiller@proxmox.com>
Wed, 21 Aug 2019 08:52:37 +0000 (10:52 +0200)
committerWolfgang Bumiller <w.bumiller@proxmox.com>
Wed, 21 Aug 2019 09:51:45 +0000 (11:51 +0200)
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
proxmox-tools/src/fd.rs

index 0b5ff05beb9a1a44d6d05d143e9452ddfb3faa96..5490e9d368815f4ff45f0c382d26d40bc8878b6d 100644 (file)
@@ -2,6 +2,10 @@
 
 use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
 
+use nix::fcntl::OFlag;
+use nix::sys::stat::Mode;
+use nix::NixPath;
+
 /// Guard a raw file descriptor with a drop handler. This is mostly useful when access to an owned
 /// `RawFd` is required without the corresponding handler object (such as when only the file
 /// descriptor number is required in a closure which may be dropped instead of being executed).
@@ -9,7 +13,8 @@ pub struct Fd(pub RawFd);
 
 impl Drop for Fd {
     fn drop(&mut self) {
-        if self.0 != -1 {
+        // `>= 0` instead of `!= -1` to also handle things like AT_FDCWD
+        if self.0 >= 0 {
             unsafe {
                 libc::close(self.0);
             }
@@ -36,3 +41,24 @@ impl FromRawFd for Fd {
         Self(fd)
     }
 }
+
+impl Fd {
+    pub const fn cwd() -> Self {
+        Self(libc::AT_FDCWD)
+    }
+
+    pub fn open<P>(path: &P, oflag: OFlag, mode: Mode) -> Result<Self, nix::Error>
+    where
+        P: ?Sized + NixPath,
+    {
+        nix::fcntl::open(path, oflag, mode).map(Self)
+    }
+
+    pub fn openat<D, P>(dirfd: D, path: &P, oflag: OFlag, mode: Mode) -> Result<Self, nix::Error>
+    where
+        D: AsRawFd,
+        P: ?Sized + NixPath,
+    {
+        nix::fcntl::openat(dirfd.as_raw_fd(), path, oflag, mode).map(Self)
+    }
+}