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
//! Provides a wrapper over `RawFd` that does not close it on drop.
//! This can be useful for aliasing file descriptors.
use super::*;

/// Represents a `RawFd` but does not provide any ownership of it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct UnmanagedFD(NonNegativeI32);

impl UnmanagedFD {
    #[inline] 
    pub fn new(alias: &(impl AsRawFd + ?Sized)) -> Self
    {
	Self(alias.as_raw_fd().into())
    }

    #[inline]
    pub const fn new_raw(raw: RawFd) -> Option<Self>
    {
	match NonNegativeI32::new(raw) {
	    Some(x) => Some(Self(x)),
	    None => None,
	}
    }

    #[inline] 
    pub(super) const fn new_or_panic(raw: RawFd) -> Self
    {
	Self(NonNegativeI32::new_or_panic(raw))
    }

    #[inline]
    pub const unsafe fn new_unchecked(raw: RawFd) -> Self
    {
	Self(NonNegativeI32::new_unchecked(raw))
    }

    #[inline] 
    pub const fn get(&self) -> RawFd
    {
	self.0.get()
    }
}

impl From<RawFd> for UnmanagedFD
{
    #[inline] 
    fn from(from: RawFd) -> Self
    {
	debug_assert!(from >= 0, "Invalid file descriptor");
	Self(from.into())
    }
}

impl From<UnmanagedFD> for RawFd
{
    #[inline] 
    fn from(from: UnmanagedFD) -> Self
    {
	from.get()
    }
}

// No impl for `IntoRawFd` because `UnmanagedFD` is not owning

impl FromRawFd for UnmanagedFD
{
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
	Self(fd.into())
    }
}


impl AsRawFd for UnmanagedFD
{
    #[inline(always)] 
    fn as_raw_fd(&self) -> RawFd {
	self.0.get()
    }
}

impl From<UnmanagedFD> for ManagedFD {
    #[inline]
    fn from(from: UnmanagedFD) -> Self {
	Self::take(unsafe { UnmanagedFD::new_unchecked( c_try!(libc::dup(from.get()) => if |x| x < 0; "dup(): failed to duplicate file descriptor {}", from.get()) ) })

    }
}

//TODO: implement a full version of the temporary struct `UnmanagedFD` from `utf8encode`