mapped_file/file/
unmanaged.rs

1//! Provides a wrapper over `RawFd` that does not close it on drop.
2//! This can be useful for aliasing file descriptors.
3use super::*;
4
5/// Represents a `RawFd` but does not provide any ownership of it.
6#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
7#[repr(transparent)]
8pub struct UnmanagedFD(NonNegativeI32);
9
10impl UnmanagedFD {
11    #[inline] 
12    pub fn new(alias: &(impl AsRawFd + ?Sized)) -> Self
13    {
14	Self(alias.as_raw_fd().into())
15    }
16
17    #[inline]
18    pub const fn new_raw(raw: RawFd) -> Option<Self>
19    {
20	match NonNegativeI32::new(raw) {
21	    Some(x) => Some(Self(x)),
22	    None => None,
23	}
24    }
25
26    #[inline] 
27    pub(super) const fn new_or_panic(raw: RawFd) -> Self
28    {
29	Self(NonNegativeI32::new_or_panic(raw))
30    }
31
32    #[inline]
33    pub const unsafe fn new_unchecked(raw: RawFd) -> Self
34    {
35	Self(NonNegativeI32::new_unchecked(raw))
36    }
37
38    #[inline] 
39    pub const fn get(&self) -> RawFd
40    {
41	self.0.get()
42    }
43}
44
45impl From<RawFd> for UnmanagedFD
46{
47    #[inline] 
48    fn from(from: RawFd) -> Self
49    {
50	debug_assert!(from >= 0, "Invalid file descriptor");
51	Self(from.into())
52    }
53}
54
55impl From<UnmanagedFD> for RawFd
56{
57    #[inline] 
58    fn from(from: UnmanagedFD) -> Self
59    {
60	from.get()
61    }
62}
63
64// No impl for `IntoRawFd` because `UnmanagedFD` is not owning
65
66impl FromRawFd for UnmanagedFD
67{
68    unsafe fn from_raw_fd(fd: RawFd) -> Self {
69	Self(fd.into())
70    }
71}
72
73
74impl AsRawFd for UnmanagedFD
75{
76    #[inline(always)] 
77    fn as_raw_fd(&self) -> RawFd {
78	self.0.get()
79    }
80}
81
82impl From<UnmanagedFD> for ManagedFD {
83    #[inline]
84    fn from(from: UnmanagedFD) -> Self {
85	Self::take(unsafe { UnmanagedFD::new_unchecked( c_try!(libc::dup(from.get()) => if |x| x < 0; "dup(): failed to duplicate file descriptor {}", from.get()) ) })
86
87    }
88}
89
90//TODO: implement a full version of the temporary struct `UnmanagedFD` from `utf8encode`