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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
use std::os::raw::c_int;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Fd(pub c_int);
#[derive(Clone, Copy)]
pub struct EncodedFd<T> {
pub(crate) raw: u32,
pub(crate) convert_fd: T,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidFd;
pub trait ConvertFd {
fn convert_fd(&self, raw: u32) -> Result<Fd, InvalidFd>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Identity;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NoConvert;
#[derive(Clone, Copy)]
pub struct ConvertFdFn<F: Fn(u32) -> Result<Fd, InvalidFd>>(pub F);
impl<T: ConvertFd> EncodedFd<T> {
pub fn new(raw: u32, convert_fd: T) -> EncodedFd<T> {
EncodedFd { raw, convert_fd }
}
pub fn raw_encoded_number(&self) -> u32 {
self.raw
}
pub fn to_fd(&self) -> Result<Fd, u32> {
self.convert_fd
.convert_fd(self.raw)
.map_err(|InvalidFd| self.raw)
}
}
impl ConvertFd for Identity {
fn convert_fd(&self, fd: u32) -> Result<Fd, InvalidFd> {
Ok(Fd(fd as c_int))
}
}
impl ConvertFd for NoConvert {
fn convert_fd(&self, _: u32) -> Result<Fd, InvalidFd> {
Err(InvalidFd)
}
}
impl<F> ConvertFd for ConvertFdFn<F>
where
F: Fn(u32) -> Result<Fd, InvalidFd>,
{
fn convert_fd(&self, fd: u32) -> Result<Fd, InvalidFd> {
self.0(fd)
}
}
impl<'a, T> ConvertFd for &'a T
where
T: ConvertFd + 'a + ?Sized,
{
fn convert_fd(&self, fd: u32) -> Result<Fd, InvalidFd> {
(*self).convert_fd(fd)
}
}
pub trait FdMapping {
fn map(&mut self, fd: Fd) -> u32;
}
impl FdMapping for Vec<Fd> {
fn map(&mut self, new_fd: Fd) -> u32 {
for (i, fd) in self.iter().enumerate() {
if fd.0 == new_fd.0 {
return i as u32;
}
}
let new_i = self.len() as u32;
self.push(new_fd);
new_i
}
}