1use std::io;
11#[cfg(unix)]
12use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd, RawFd};
13#[cfg(unix)]
14use std::os::unix::net::UnixDatagram;
15use std::time::Duration;
16
17pub const MAX_DATAGRAM: usize = 65_535;
19
20#[derive(Debug)]
22pub struct Datagram {
23 #[cfg(unix)]
24 socket: UnixDatagram,
25 #[cfg(windows)]
26 stream: crate::Stream,
27 #[cfg(not(any(unix, windows)))]
28 never: std::convert::Infallible,
29}
30
31impl Datagram {
32 pub fn pair() -> io::Result<(Self, Self)> {
37 #[cfg(unix)]
38 {
39 let (ours, theirs) = UnixDatagram::pair()?;
40 Ok((Self { socket: ours }, Self { socket: theirs }))
41 }
42 #[cfg(windows)]
43 {
44 let (ours, theirs) = crate::link::pair()?;
45 Ok((Self { stream: ours }, Self { stream: theirs }))
46 }
47 #[cfg(not(any(unix, windows)))]
48 {
49 Err(io::Error::new(
50 io::ErrorKind::Unsupported,
51 "a page has no local socket",
52 ))
53 }
54 }
55
56 pub fn send(&self, payload: &[u8]) -> io::Result<usize> {
61 if payload.len() > MAX_DATAGRAM {
62 return Err(too_long(payload.len()));
63 }
64 #[cfg(unix)]
65 {
66 self.socket.send(payload)
67 }
68 #[cfg(windows)]
69 {
70 use std::io::Write as _;
71 (&self.stream).write_all(&framed(payload))?;
72 Ok(payload.len())
73 }
74 #[cfg(not(any(unix, windows)))]
75 {
76 match self.never {}
77 }
78 }
79
80 pub fn recv(&self, buffer: &mut [u8]) -> io::Result<usize> {
88 #[cfg(unix)]
89 {
90 self.socket.recv(buffer)
91 }
92 #[cfg(windows)]
93 {
94 let mut header = [0_u8; HEADER];
95 if !self.fill(&mut header, false)? {
96 return Ok(0);
97 }
98 let length = usize::try_from(u32::from_le_bytes(header)).unwrap_or(usize::MAX);
99 if length > MAX_DATAGRAM {
100 return Err(too_long(length));
101 }
102 let kept = length.min(buffer.len());
103 let mut rest = vec![0_u8; length.saturating_sub(kept)];
104 let whole = self.fill(buffer.get_mut(..kept).unwrap_or_default(), true)?
105 && self.fill(&mut rest, true)?;
106 Ok(if whole { kept } else { 0 })
107 }
108 #[cfg(not(any(unix, windows)))]
109 {
110 let _ = buffer;
111 match self.never {}
112 }
113 }
114
115 #[cfg(windows)]
119 fn fill(&self, into: &mut [u8], begun: bool) -> io::Result<bool> {
120 use std::io::Read as _;
121 let mut at = 0;
122 while let Some(left) = into.get_mut(at..).filter(|left| !left.is_empty()) {
123 match (&self.stream).read(left) {
124 Ok(0) => return Ok(false),
125 Ok(read) => at = at.saturating_add(read),
126 Err(error)
127 if (begun || at > 0)
128 && matches!(
129 error.kind(),
130 io::ErrorKind::WouldBlock
131 | io::ErrorKind::TimedOut
132 | io::ErrorKind::Interrupted
133 ) => {}
134 Err(error) => return Err(error),
135 }
136 }
137 Ok(true)
138 }
139
140 pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
145 #[cfg(unix)]
146 {
147 self.socket.set_read_timeout(timeout)
148 }
149 #[cfg(windows)]
150 {
151 self.stream.set_read_timeout(timeout)
152 }
153 #[cfg(not(any(unix, windows)))]
154 {
155 let _ = timeout;
156 match self.never {}
157 }
158 }
159
160 pub fn try_clone(&self) -> io::Result<Self> {
165 #[cfg(unix)]
166 {
167 Ok(Self {
168 socket: self.socket.try_clone()?,
169 })
170 }
171 #[cfg(windows)]
172 {
173 Ok(Self {
174 stream: self.stream.try_clone()?,
175 })
176 }
177 #[cfg(not(any(unix, windows)))]
178 {
179 match self.never {}
180 }
181 }
182
183 #[cfg(unix)]
184 pub(crate) fn into_socket(self) -> UnixDatagram {
185 self.socket
186 }
187
188 #[cfg(windows)]
189 pub(crate) fn into_stream(self) -> crate::Stream {
190 self.stream
191 }
192}
193
194#[cfg(windows)]
196pub(crate) const HEADER: usize = 4;
197
198#[cfg(windows)]
200pub(crate) fn framed(payload: &[u8]) -> Vec<u8> {
201 let length = u32::try_from(payload.len()).unwrap_or(u32::MAX);
202 let mut framed = Vec::with_capacity(HEADER.saturating_add(payload.len()));
203 framed.extend_from_slice(&length.to_le_bytes());
204 framed.extend_from_slice(payload);
205 framed
206}
207
208pub(crate) fn too_long(length: usize) -> io::Error {
209 io::Error::new(
210 io::ErrorKind::InvalidInput,
211 format!("a datagram of {length} bytes is longer than the {MAX_DATAGRAM} one carries"),
212 )
213}
214
215#[cfg(unix)]
217impl From<OwnedFd> for Datagram {
218 fn from(fd: OwnedFd) -> Self {
219 Self {
220 socket: UnixDatagram::from(fd),
221 }
222 }
223}
224
225#[cfg(unix)]
226impl AsFd for Datagram {
227 fn as_fd(&self) -> BorrowedFd<'_> {
228 self.socket.as_fd()
229 }
230}
231
232#[cfg(unix)]
233impl AsRawFd for Datagram {
234 fn as_raw_fd(&self) -> RawFd {
235 self.socket.as_raw_fd()
236 }
237}
238
239#[cfg(test)]
240#[cfg(any(unix, windows))]
241mod tests {
242 use super::Datagram;
243 use std::time::Duration;
244
245 #[test]
246 fn a_datagram_arrives_whole_and_cut_to_the_buffer() {
247 let (ours, theirs) = Datagram::pair().unwrap();
248 ours.send(b"first").unwrap();
249 ours.send(&[7; 3000]).unwrap();
250 ours.send(b"third").unwrap();
251 let mut buffer = [0_u8; 16];
252 assert_eq!(theirs.recv(&mut buffer).unwrap(), 5);
253 assert_eq!(&buffer[..5], b"first");
254 assert_eq!(theirs.recv(&mut buffer).unwrap(), 16);
256 assert_eq!(buffer, [7; 16]);
257 assert_eq!(theirs.recv(&mut buffer).unwrap(), 5);
258 assert_eq!(&buffer[..5], b"third");
259 }
260
261 #[test]
262 fn a_read_waits_no_longer_than_its_timeout() {
263 let (_ours, theirs) = Datagram::pair().unwrap();
264 theirs
265 .set_read_timeout(Some(Duration::from_millis(50)))
266 .unwrap();
267 let waited = theirs.recv(&mut [0_u8; 8]).unwrap_err();
268 assert!(
269 matches!(
270 waited.kind(),
271 std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
272 ),
273 "{waited}"
274 );
275 }
276}