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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
use static_assertions::assert_impl_all;
use std::os::unix::io;

use crate::{Basic, EncodingFormat, Signature, Type};

/// A [`RawFd`](https://doc.rust-lang.org/std/os/unix/io/type.RawFd.html) wrapper.
///
/// See also `OwnedFd` if you need a wrapper that takes ownership of the file.
///
/// We wrap the `RawFd` type so that we can implement [`Serialize`] and [`Deserialize`] for it.
/// File descriptors are serialized in a special way and you need to use specific [serializer] and
/// [deserializer] API when file descriptors are or could be involved.
///
/// [`Serialize`]: https://docs.serde.rs/serde/trait.Serialize.html
/// [`Deserialize`]: https://docs.serde.rs/serde/de/trait.Deserialize.html
/// [deserializer]: fn.from_slice_fds.html
/// [serializer]: fn.to_bytes_fds.html
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct Fd(io::RawFd);

macro_rules! fd_impl {
    ($i:ident) => {
        assert_impl_all!($i: Send, Sync, Unpin);

        impl Basic for $i {
            const SIGNATURE_CHAR: char = 'h';
            const SIGNATURE_STR: &'static str = "h";

            fn alignment(format: EncodingFormat) -> usize {
                u32::alignment(format)
            }
        }

        impl Type for $i {
            fn signature() -> Signature<'static> {
                Signature::from_static_str_unchecked(Self::SIGNATURE_STR)
            }
        }
    };
}

fd_impl!(Fd);

impl Serialize for Fd {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i32(self.0)
    }
}

impl<'de> Deserialize<'de> for Fd {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Fd(i32::deserialize(deserializer)?))
    }
}

impl From<io::RawFd> for Fd {
    fn from(value: io::RawFd) -> Self {
        Self(value)
    }
}

impl<T> From<&T> for Fd
where
    T: io::AsRawFd,
{
    fn from(t: &T) -> Self {
        Self(t.as_raw_fd())
    }
}

impl io::AsRawFd for Fd {
    fn as_raw_fd(&self) -> io::RawFd {
        self.0
    }
}

impl std::fmt::Display for Fd {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// An owned [`RawFd`](https://doc.rust-lang.org/std/os/unix/io/type.RawFd.html) wrapper.
///
/// See also [`Fd`]. This type owns the file and will close it on drop. On deserialize, it will
/// duplicate the file descriptor.
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct OwnedFd {
    inner: io::RawFd,
}

impl Drop for OwnedFd {
    fn drop(&mut self) {
        unsafe {
            libc::close(self.inner);
        }
    }
}

fd_impl!(OwnedFd);

impl Serialize for OwnedFd {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i32(self.inner)
    }
}

impl<'de> Deserialize<'de> for OwnedFd {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let fd = unsafe { libc::dup(i32::deserialize(deserializer)?) };
        if fd < 0 {
            return Err(D::Error::custom(std::io::Error::last_os_error()));
        }
        Ok(OwnedFd { inner: fd })
    }
}

impl io::FromRawFd for OwnedFd {
    unsafe fn from_raw_fd(fd: io::RawFd) -> Self {
        Self { inner: fd }
    }
}

impl io::AsRawFd for OwnedFd {
    fn as_raw_fd(&self) -> io::RawFd {
        self.inner
    }
}

impl io::IntoRawFd for OwnedFd {
    fn into_raw_fd(self) -> io::RawFd {
        let fd = self.inner;
        std::mem::forget(self);
        fd
    }
}

impl std::fmt::Display for OwnedFd {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}