tokio_uds/
send_dgram.rs

1use UnixDatagram;
2
3use futures::{Async, Future, Poll};
4
5use std::io;
6use std::mem;
7use std::path::Path;
8
9/// A future for writing a buffer to a Unix datagram socket.
10#[derive(Debug)]
11pub struct SendDgram<T, P> {
12    st: State<T, P>,
13}
14
15#[derive(Debug)]
16enum State<T, P> {
17    /// current state is Sending
18    Sending {
19        /// the underlying socket
20        sock: UnixDatagram,
21        /// the buffer to send
22        buf: T,
23        /// the destination
24        addr: P,
25    },
26    /// neutral state
27    Empty,
28}
29
30impl<T, P> SendDgram<T, P>
31where
32    T: AsRef<[u8]>,
33    P: AsRef<Path>,
34{
35    pub(crate) fn new(sock: UnixDatagram, buf: T, addr: P) -> SendDgram<T, P> {
36        SendDgram {
37            st: State::Sending { sock, buf, addr },
38        }
39    }
40}
41
42impl<T, P> Future for SendDgram<T, P>
43where
44    T: AsRef<[u8]>,
45    P: AsRef<Path>,
46{
47    /// Returns the underlying socket and the buffer that was sent.
48    type Item = (UnixDatagram, T);
49    /// The error that is returned when sending failed.
50    type Error = io::Error;
51
52    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
53        if let State::Sending {
54            ref mut sock,
55            ref buf,
56            ref addr,
57        } = self.st
58        {
59            let n = try_ready!(sock.poll_send_to(buf.as_ref(), addr));
60            if n < buf.as_ref().len() {
61                return Err(io::Error::new(
62                    io::ErrorKind::Other,
63                    "Couldn't send whole buffer".to_string(),
64                ));
65            }
66        } else {
67            panic!()
68        }
69        if let State::Sending { sock, buf, addr: _ } = mem::replace(&mut self.st, State::Empty) {
70            Ok(Async::Ready((sock, buf)))
71        } else {
72            panic!()
73        }
74    }
75}