From d96bb7f163f33787ce48146b3bb93aa003c5f477 Mon Sep 17 00:00:00 2001 From: Wolfgang Bumiller Date: Wed, 10 Apr 2019 15:14:05 +0200 Subject: [PATCH] tools: add Fd helper stores a raw file descriptor with a drop handler for safekeeping in closures Signed-off-by: Wolfgang Bumiller --- src/tools.rs | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/src/tools.rs b/src/tools.rs index fda9829d..f5ed3296 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -14,8 +14,7 @@ use std::io::Read; use std::io::ErrorKind; use std::time::Duration; -use std::os::unix::io::RawFd; -use std::os::unix::io::AsRawFd; +use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::collections::HashMap; @@ -641,3 +640,38 @@ pub fn fail_on_shutdown() -> Result<(), Error> { } Ok(()) } + +/// 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). +pub struct Fd(pub RawFd); + +impl Drop for Fd { + fn drop(&mut self) { + if self.0 != -1 { + unsafe { + libc::close(self.0); + } + } + } +} + +impl AsRawFd for Fd { + fn as_raw_fd(&self) -> RawFd { + self.0 + } +} + +impl IntoRawFd for Fd { + fn into_raw_fd(mut self) -> RawFd { + let fd = self.0; + self.0 = -1; + fd + } +} + +impl FromRawFd for Fd { + unsafe fn from_raw_fd(fd: RawFd) -> Self { + Self(fd) + } +}