Files
adler32
aho_corasick
ansi_term
atty
backtrace
backtrace_sys
base64
base_x
bitflags
block_buffer
block_padding
bstr
byte_tools
byteorder
bytes
cargo_metadata
cargo_web
cfg_if
clap
cookie
cookie_store
crc32fast
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_queue
crossbeam_utils
digest
directories
dirs_sys
dtoa
either
embed_wasm
embed_wasm_build
encoding_rs
env_logger
error_chain
failure
failure_derive
fake_simd
filetime
flate2
fnv
foreign_types
foreign_types_shared
futures
futures_channel
futures_core
futures_cpupool
futures_sink
futures_task
futures_util
generic_array
getrandom
globset
h2
handlebars
headers
headers_core
heck
http
http_body
httparse
humantime
hyper
hyper_tls
idna
ignore
indexmap
inotify
inotify_sys
iovec
itoa
language_tags
lazy_static
lazycell
libc
libflate
lock_api
log
maplit
matches
maybe_uninit
memchr
memmap
memoffset
mime
mime_guess
miniz_oxide
mio
mio_extras
mio_uds
native_tls
net2
notify
num_cpus
opaque_debug
open
openssl
openssl_probe
openssl_sys
parity_wasm
parking_lot
parking_lot_core
pbr
percent_encoding
pest
pest_derive
pest_generator
pest_meta
phf
phf_codegen
phf_generator
phf_shared
pin_project
pin_project_internal
pin_project_lite
pin_utils
ppv_lite86
proc_macro2
publicsuffix
quick_error
quote
rand
rand_chacha
rand_core
rand_hc
rand_isaac
rand_jitter
rand_os
rand_pcg
rand_xorshift
regex
regex_syntax
remove_dir_all
reqwest
rle_decode_fast
rustc_demangle
ryu
safemem
same_file
scoped_tls
scopeguard
semver
semver_parser
serde
serde_derive
serde_json
serde_urlencoded
sha1
sha2
siphasher
slab
smallvec
string
strsim
structopt
structopt_derive
syn
synstructure
take_mut
tar
tempfile
termcolor
textwrap
thread_local
time
tokio
tokio_buf
tokio_codec
tokio_core
tokio_current_thread
tokio_executor
tokio_fs
tokio_io
tokio_reactor
tokio_sync
tokio_tcp
tokio_threadpool
tokio_timer
tokio_tls
tokio_udp
tokio_uds
tokio_util
toml
tower_service
traitobject
try_from
try_lock
typeable
typenum
ucd_trie
unicase
unicode_bidi
unicode_categories
unicode_normalization
unicode_segmentation
unicode_width
unicode_xid
url
uuid
vec_map
walkdir
want
websocket
xattr
  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
use std::io;
use std::os::unix::net::SocketAddr;
use std::path::Path;

use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream};

use super::UnixDatagram;

use bytes::{BufMut, BytesMut};
use tokio_codec::{Decoder, Encoder};

/// A unified `Stream` and `Sink` interface to an underlying `UnixDatagram`, using
/// the `Encoder` and `Decoder` traits to encode and decode frames.
///
/// Unix datagram sockets work with datagrams, but higher-level code may wants to
/// batch these into meaningful chunks, called "frames". This method layers
/// framing on top of this socket by using the `Encoder` and `Decoder` traits to
/// handle encoding and decoding of messages frames. Note that the incoming and
/// outgoing frame types may be distinct.
///
/// This function returns a *single* object that is both `Stream` and `Sink`;
/// grouping this into a single object is often useful for layering things which
/// require both read and write access to the underlying object.
///
/// If you want to work more directly with the streams and sink, consider
/// calling `split` on the `UnixDatagramFramed` returned by this method, which will break
/// them into separate objects, allowing them to interact more easily.
#[must_use = "sinks do nothing unless polled"]
#[derive(Debug)]
pub struct UnixDatagramFramed<A, C> {
    socket: UnixDatagram,
    codec: C,
    rd: BytesMut,
    wr: BytesMut,
    out_addr: Option<A>,
    flushed: bool,
}

impl<A, C: Decoder> Stream for UnixDatagramFramed<A, C> {
    type Item = (C::Item, SocketAddr);
    type Error = C::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        self.rd.reserve(INITIAL_RD_CAPACITY);

        let (n, addr) = unsafe {
            let (n, addr) = try_ready!(self.socket.poll_recv_from(self.rd.bytes_mut()));
            self.rd.advance_mut(n);
            (n, addr)
        };
        trace!("received {} bytes, decoding", n);
        let frame_res = self.codec.decode(&mut self.rd);
        self.rd.clear();
        let frame = frame_res?;
        let result = frame.map(|frame| (frame, addr));
        trace!("frame decoded from buffer");
        Ok(Async::Ready(result))
    }
}

impl<A: AsRef<Path>, C: Encoder> Sink for UnixDatagramFramed<A, C> {
    type SinkItem = (C::Item, A);
    type SinkError = C::Error;

    fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
        trace!("sending frame");

        if !self.flushed {
            match self.poll_complete()? {
                Async::Ready(()) => {}
                Async::NotReady => return Ok(AsyncSink::NotReady(item)),
            }
        }

        let (frame, out_addr) = item;
        self.codec.encode(frame, &mut self.wr)?;
        self.out_addr = Some(out_addr);
        self.flushed = false;
        trace!("frame encoded; length={}", self.wr.len());

        Ok(AsyncSink::Ready)
    }

    fn poll_complete(&mut self) -> Poll<(), C::Error> {
        if self.flushed {
            return Ok(Async::Ready(()));
        }

        let n = {
            let out_path = match self.out_addr {
                Some(ref out_path) => out_path.as_ref(),
                None => {
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        "internal error: addr not available while data not flushed",
                    )
                    .into());
                }
            };

            trace!("flushing frame; length={}", self.wr.len());
            try_ready!(self.socket.poll_send_to(&self.wr, out_path))
        };

        trace!("written {}", n);

        let wrote_all = n == self.wr.len();
        self.wr.clear();
        self.flushed = true;

        if wrote_all {
            self.out_addr = None;
            Ok(Async::Ready(()))
        } else {
            Err(io::Error::new(
                io::ErrorKind::Other,
                "failed to write entire datagram to socket",
            )
            .into())
        }
    }

    fn close(&mut self) -> Poll<(), C::Error> {
        self.poll_complete()
    }
}

const INITIAL_RD_CAPACITY: usize = 64 * 1024;
const INITIAL_WR_CAPACITY: usize = 8 * 1024;

impl<A, C> UnixDatagramFramed<A, C> {
    /// Create a new `UnixDatagramFramed` backed by the given socket and codec.
    ///
    /// See struct level documentation for more details.
    pub fn new(socket: UnixDatagram, codec: C) -> UnixDatagramFramed<A, C> {
        UnixDatagramFramed {
            socket: socket,
            codec: codec,
            out_addr: None,
            rd: BytesMut::with_capacity(INITIAL_RD_CAPACITY),
            wr: BytesMut::with_capacity(INITIAL_WR_CAPACITY),
            flushed: true,
        }
    }

    /// Returns a reference to the underlying I/O stream wrapped by `Framed`.
    ///
    /// # Note
    ///
    /// Care should be taken to not tamper with the underlying stream of data
    /// coming in as it may corrupt the stream of frames otherwise being worked
    /// with.
    pub fn get_ref(&self) -> &UnixDatagram {
        &self.socket
    }

    /// Returns a mutable reference to the underlying I/O stream wrapped by
    /// `Framed`.
    ///
    /// # Note
    ///
    /// Care should be taken to not tamper with the underlying stream of data
    /// coming in as it may corrupt the stream of frames otherwise being worked
    /// with.
    pub fn get_mut(&mut self) -> &mut UnixDatagram {
        &mut self.socket
    }
}