fd_passing/
types.rs

1use std::os::unix::io::{RawFd, IntoRawFd, FromRawFd};
2
3use std::fs::{self, File};
4use std::net::{self, TcpStream, TcpListener, UdpSocket};
5use std::os::unix::net::{UnixStream, UnixListener, UnixDatagram};
6use std::os::unix;
7
8use libc::c_int;
9
10pub enum FdImplementor {
11    File(File),
12    TcpStream(TcpStream),
13    TcpListener(TcpListener),
14    UdpSocket(UdpSocket),
15    UnixStream(UnixStream),
16    UnixListener(UnixListener),
17    UnixDatagram(UnixDatagram),
18}
19
20#[doc(hidden)]
21impl FdImplementor {
22    pub fn from(fdtype: c_int, rawfd: c_int) -> Option<FdImplementor> {
23        unsafe {
24            Some(match fdtype {
25                0 => FdImplementor::File(fs::File::from_raw_fd(rawfd)),
26                1 => FdImplementor::TcpStream(net::TcpStream::from_raw_fd(rawfd)),
27                2 => FdImplementor::TcpListener(net::TcpListener::from_raw_fd(rawfd)),
28                3 => FdImplementor::UdpSocket(net::UdpSocket::from_raw_fd(rawfd)),
29                4 => FdImplementor::UnixStream(unix::net::UnixStream::from_raw_fd(rawfd)),
30                5 => FdImplementor::UnixListener(unix::net::UnixListener::from_raw_fd(rawfd)),
31                6 => FdImplementor::UnixDatagram(unix::net::UnixDatagram::from_raw_fd(rawfd)),
32                _ => return None,
33            })
34        }
35    }
36
37    pub fn to(self) -> (RawFd, c_int) {
38        match self {
39            FdImplementor::File(obj)         => (obj.into_raw_fd(), 0),
40            FdImplementor::TcpStream(obj)    => (obj.into_raw_fd(), 1),
41            FdImplementor::TcpListener(obj)  => (obj.into_raw_fd(), 2),
42            FdImplementor::UdpSocket(obj)    => (obj.into_raw_fd(), 3),
43            FdImplementor::UnixStream(obj)   => (obj.into_raw_fd(), 4),
44            FdImplementor::UnixListener(obj) => (obj.into_raw_fd(), 5),
45            FdImplementor::UnixDatagram(obj) => (obj.into_raw_fd(), 6),
46        }
47    }
48}