tools: add Fd helper
stores a raw file descriptor with a drop handler for safekeeping in closures Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
		
							
								
								
									
										38
									
								
								src/tools.rs
									
									
									
									
									
								
							
							
						
						
									
										38
									
								
								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) | ||||
|     } | ||||
| } | ||||
|  | ||||
		Reference in New Issue
	
	Block a user