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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#![feature(type_alias_impl_trait)]
use std::{
future::Future,
io::Result,
os::{fd::OwnedFd, unix::io::RawFd},
pin::Pin,
task::{ready, Context, Poll},
};
pub trait OwnedFds: Extend<OwnedFd> {
fn len(&self) -> usize;
fn capacity(&self) -> Option<usize>;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn take<T: Extend<OwnedFd>>(&mut self, fds: &mut T);
}
impl OwnedFds for Vec<OwnedFd> {
#[inline]
fn len(&self) -> usize {
Vec::len(self)
}
#[inline]
fn capacity(&self) -> Option<usize> {
None
}
#[inline]
fn take<T: Extend<OwnedFd>>(&mut self, fds: &mut T) {
fds.extend(self.drain(..))
}
}
pub trait AsyncWriteWithFd {
fn poll_write_with_fds<Fds: OwnedFds>(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
fds: &mut Fds,
) -> Poll<Result<usize>>;
}
impl<T: AsyncWriteWithFd + Unpin> AsyncWriteWithFd for &mut T {
#[inline]
fn poll_write_with_fds<Fds: OwnedFds>(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
fds: &mut Fds,
) -> Poll<Result<usize>> {
Pin::new(&mut **self).poll_write_with_fds(cx, buf, fds)
}
}
pub struct Send<'a, W: WriteMessage + ?Sized + 'a, M: ser::Serialize + Unpin + std::fmt::Debug + 'a>
{
writer: &'a mut W,
object_id: u32,
msg: Option<M>,
}
pub struct Flush<'a, W: WriteMessage + ?Sized + 'a> {
writer: &'a mut W,
}
impl<
'a,
W: WriteMessage + Unpin + ?Sized + 'a,
M: ser::Serialize + Unpin + std::fmt::Debug + 'a,
> Future for Send<'a, W, M>
{
type Output = std::io::Result<()>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
let mut sink = Pin::new(&mut *this.writer);
ready!(sink.as_mut().poll_ready(cx))?;
sink.start_send(this.object_id, this.msg.take().unwrap());
Poll::Ready(Ok(()))
}
}
impl<'a, W: WriteMessage + Unpin + ?Sized + 'a> Future for Flush<'a, W> {
type Output = std::io::Result<()>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
Pin::new(&mut *this.writer).poll_flush(cx)
}
}
pub trait WriteMessage {
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>>;
fn start_send<M: ser::Serialize + std::fmt::Debug>(
self: Pin<&mut Self>,
object_id: u32,
msg: M,
);
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>>;
#[must_use]
fn send<'a, 'b, 'c, M: ser::Serialize + Unpin + std::fmt::Debug + 'b>(
&'a mut self,
object_id: u32,
msg: M,
) -> Send<'c, Self, M>
where
Self: Unpin,
'a: 'c,
'b: 'c,
{
Send {
writer: self,
object_id,
msg: Some(msg),
}
}
#[must_use]
fn flush(&mut self) -> Flush<'_, Self>
where
Self: Unpin,
{
Flush { writer: self }
}
}
pub trait AsyncReadWithFd {
fn poll_read_with_fds<Fds: OwnedFds>(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
fds: &mut Fds,
) -> Poll<Result<usize>>;
}
impl<T: AsyncReadWithFd + Unpin> AsyncReadWithFd for &mut T {
fn poll_read_with_fds<Fds: OwnedFds>(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
fds: &mut Fds,
) -> Poll<Result<usize>> {
Pin::new(&mut **self).poll_read_with_fds(cx, buf, fds)
}
}
pub mod ser {
use std::os::fd::OwnedFd;
use bytes::BytesMut;
#[allow(clippy::len_without_is_empty)]
pub trait Serialize {
fn serialize<Fds: Extend<OwnedFd>>(self, buf: &mut BytesMut, fds: &mut Fds);
fn len(&self) -> u16;
fn nfds(&self) -> u8;
}
}
pub mod de {
use std::{convert::Infallible, os::unix::io::RawFd};
pub enum Error {
InvalidIntEnum(i32, &'static str),
InvalidUintEnum(u32, &'static str),
UnknownOpcode(u32, &'static str),
TrailingData(u32, u32),
MissingNul(&'static str),
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::InvalidIntEnum(v, name) =>
write!(f, "int {v} is not a valid value for {name}"),
Error::InvalidUintEnum(v, name) =>
write!(f, "uint {v} is not a valid value for {name}"),
Error::UnknownOpcode(v, name) => write!(f, "opcode {v} is not valid for {name}"),
Error::TrailingData(expected, got) => write!(
f,
"message trailing bytes, expected {expected} bytes, got {got} bytes"
),
Error::MissingNul(name) =>
write!(f, "string value for {name} is missing the NUL terminator"),
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self, f)
}
}
impl std::error::Error for Error {}
pub trait Deserialize<'a>: Sized {
fn deserialize(data: &'a [u8], fds: &'a [RawFd]) -> Result<Self, Error>;
}
impl<'a> Deserialize<'a> for Infallible {
fn deserialize(_: &'a [u8], _: &'a [RawFd]) -> Result<Self, Error> {
Err(Error::UnknownOpcode(0, "unexpected message for object"))
}
}
impl<'a> Deserialize<'a> for (&'a [u8], &'a [RawFd]) {
fn deserialize(data: &'a [u8], fds: &'a [RawFd]) -> Result<Self, Error> {
Ok((data, fds))
}
}
}
pub mod buf {
use std::{future::Future, io::Result, task::ready};
use super::*;
pub struct Message<'a> {
pub object_id: u32,
pub len: usize,
pub data: &'a [u8],
pub fds: &'a [RawFd],
}
pub unsafe trait AsyncBufReadWithFd: AsyncReadWithFd {
fn poll_fill_buf_until<'a>(
self: Pin<&'a mut Self>,
cx: &mut Context<'_>,
len: usize,
) -> Poll<Result<()>>;
fn fds(&self) -> &[RawFd];
fn buffer(&self) -> &[u8];
fn consume(self: Pin<&mut Self>, amt: usize, amt_fd: usize);
fn fill_buf_until(&mut self, len: usize) -> FillBufUtil<'_, Self>
where
Self: Unpin,
{
FillBufUtil(Some(self), len)
}
fn poll_next_message<'a>(
mut self: Pin<&'a mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<Message<'a>>> {
let (object_id, len) = {
ready!(self.as_mut().poll_fill_buf_until(cx, 8))?;
let object_id = self
.buffer()
.get(..4)
.expect("Bug in poll_fill_buf_until implementation");
let object_id =
unsafe { u32::from_ne_bytes(*(object_id.as_ptr() as *const [u8; 4])) };
let header = self
.buffer()
.get(4..8)
.expect("Bug in poll_fill_buf_until implementation");
let header = unsafe { u32::from_ne_bytes(*(header.as_ptr() as *const [u8; 4])) };
(object_id, (header >> 16) as usize)
};
ready!(self.as_mut().poll_fill_buf_until(cx, len))?;
let this = self.into_ref().get_ref();
Poll::Ready(Ok(Message {
object_id,
len,
data: &this.buffer()[..len],
fds: this.fds(),
}))
}
fn next_message<'a>(self: Pin<&'a mut Self>) -> NextMessageFut<'a, Self>
where
Self: Sized,
{
pub struct NextMessage<'a, R>(Option<Pin<&'a mut R>>);
impl<'a, R> Future for NextMessage<'a, R>
where
R: AsyncBufReadWithFd,
{
type Output = Result<Message<'a>>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
let mut reader = this.0.take().expect("NextMessage polled after completion");
match reader.as_mut().poll_next_message(cx) {
Poll::Pending => {
this.0 = Some(reader);
Poll::Pending
},
Poll::Ready(Ok(_)) => match reader.poll_next_message(cx) {
Poll::Pending => {
panic!("poll_next_message returned Ready, but then Pending again")
},
ready => ready,
},
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
}
}
}
NextMessage(Some(self))
}
}
pub struct FillBufUtil<'a, R: Unpin + ?Sized>(Option<&'a mut R>, usize);
impl<'a, R: AsyncBufReadWithFd + Unpin> ::std::future::Future for FillBufUtil<'a, R> {
type Output = Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
let len = this.1;
let inner = this.0.take().expect("FillBufUtil polled after completion");
match Pin::new(&mut *inner).poll_fill_buf_until(cx, len) {
Poll::Pending => {
this.0 = Some(inner);
Poll::Pending
},
ready => ready,
}
}
}
pub type NextMessageFut<'a, T: AsyncBufReadWithFd + 'a> =
impl Future<Output = Result<Message<'a>>> + 'a;
}