Files
adler32
aho_corasick
approx
arrayvec
ascii
backtrace
backtrace_sys
base64
bitflags
brotli2
brotli_sys
bstr
buf_redux
byteorder
bytes
cfg_if
chrono
chunked_transfer
color_quant
cookie
cookie_store
crc32fast
crossbeam_deque
crossbeam_epoch
crossbeam_queue
crossbeam_utils
csv
csv_core
csv_user_import
deflate
diesel
associations
connection
expression
expression_methods
macros
migration
mysql
query_builder
query_dsl
query_source
sql_types
type_impls
types
diesel_derives
diesel_migrations
dirs
dotenv
dtoa
either
encoding_rs
error_chain
failure
failure_derive
filetime
flate2
fnv
foreign_types
foreign_types_shared
futures
futures_cpupool
gif
google_signin
gzip_header
h2
http
http_body
httparse
hyper
hyper_rustls
hyper_tls
idna
image
indexmap
inflate
iovec
itoa
jpeg_decoder
language_tags
lazy_static
libc
lock_api
log
lzw
matches
memchr
memoffset
migrations_internals
migrations_macros
mime
mime_guess
miniz_oxide
mio
multipart
mysqlclient_sys
native_tls
net2
nodrop
num_cpus
num_derive
num_integer
num_iter
num_rational
num_traits
openssl
openssl_probe
openssl_sys
ordered_float
owning_ref
parking_lot
parking_lot_core
percent_encoding
phf
phf_shared
png
proc_macro2
publicsuffix
quick_error
quote
r2d2
rand
rand_chacha
rand_core
rand_hc
rand_isaac
rand_jitter
rand_os
rand_pcg
rand_xorshift
rayon
rayon_core
regex
regex_automata
regex_syntax
remove_dir_all
reqwest
ring
rouille
rustc_demangle
rustls
rusttype
ryu
safemem
scheduled_thread_pool
scoped_threadpool
scopeguard
sct
serde
serde_derive
serde_json
serde_urlencoded
sha1
simplelog
siphasher
slab
smallvec
stable_deref_trait
stb_truetype
string
syn
synom
synstructure
tempdir
term
thread_local
threadpool
tiff
time
tiny_http
tokio
tokio_buf
tokio_current_thread
tokio_executor
tokio_io
tokio_reactor
tokio_sync
tokio_tcp
tokio_threadpool
tokio_timer
traitobject
try_from
try_lock
twoway
typeable
unicase
unicode_bidi
unicode_normalization
unicode_xid
untrusted
url
uuid
want
webdev_lib
webpki
webpki_roots
  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
use codec::UserError;
use codec::UserError::*;
use frame::{self, Frame, FrameSize};
use hpack;

use bytes::{Buf, BufMut, BytesMut};
use futures::*;
use tokio_io::{AsyncRead, AsyncWrite};

use std::io::{self, Cursor};

#[derive(Debug)]
pub struct FramedWrite<T, B> {
    /// Upstream `AsyncWrite`
    inner: T,

    /// HPACK encoder
    hpack: hpack::Encoder,

    /// Write buffer
    ///
    /// TODO: Should this be a ring buffer?
    buf: Cursor<BytesMut>,

    /// Next frame to encode
    next: Option<Next<B>>,

    /// Last data frame
    last_data_frame: Option<frame::Data<B>>,

    /// Max frame size, this is specified by the peer
    max_frame_size: FrameSize,
}

#[derive(Debug)]
enum Next<B> {
    Data(frame::Data<B>),
    Continuation(frame::Continuation),
}

/// Initialze the connection with this amount of write buffer.
///
/// The minimum MAX_FRAME_SIZE is 16kb, so always be able to send a HEADERS
/// frame that big.
const DEFAULT_BUFFER_CAPACITY: usize = 16 * 1_024;

/// Min buffer required to attempt to write a frame
const MIN_BUFFER_CAPACITY: usize = frame::HEADER_LEN + CHAIN_THRESHOLD;

/// Chain payloads bigger than this. The remote will never advertise a max frame
/// size less than this (well, the spec says the max frame size can't be less
/// than 16kb, so not even close).
const CHAIN_THRESHOLD: usize = 256;

// TODO: Make generic
impl<T, B> FramedWrite<T, B>
where
    T: AsyncWrite,
    B: Buf,
{
    pub fn new(inner: T) -> FramedWrite<T, B> {
        FramedWrite {
            inner: inner,
            hpack: hpack::Encoder::default(),
            buf: Cursor::new(BytesMut::with_capacity(DEFAULT_BUFFER_CAPACITY)),
            next: None,
            last_data_frame: None,
            max_frame_size: frame::DEFAULT_MAX_FRAME_SIZE,
        }
    }

    /// Returns `Ready` when `send` is able to accept a frame
    ///
    /// Calling this function may result in the current contents of the buffer
    /// to be flushed to `T`.
    pub fn poll_ready(&mut self) -> Poll<(), io::Error> {
        if !self.has_capacity() {
            // Try flushing
            self.flush()?;

            if !self.has_capacity() {
                return Ok(Async::NotReady);
            }
        }

        Ok(Async::Ready(()))
    }

    /// Buffer a frame.
    ///
    /// `poll_ready` must be called first to ensure that a frame may be
    /// accepted.
    pub fn buffer(&mut self, item: Frame<B>) -> Result<(), UserError> {
        // Ensure that we have enough capacity to accept the write.
        assert!(self.has_capacity());

        debug!("send; frame={:?}", item);

        match item {
            Frame::Data(mut v) => {
                // Ensure that the payload is not greater than the max frame.
                let len = v.payload().remaining();

                if len > self.max_frame_size() {
                    return Err(PayloadTooBig);
                }

                if len >= CHAIN_THRESHOLD {
                    let head = v.head();

                    // Encode the frame head to the buffer
                    head.encode(len, self.buf.get_mut());

                    // Save the data frame
                    self.next = Some(Next::Data(v));
                } else {
                    v.encode_chunk(self.buf.get_mut());

                    // The chunk has been fully encoded, so there is no need to
                    // keep it around
                    assert_eq!(v.payload().remaining(), 0, "chunk not fully encoded");

                    // Save off the last frame...
                    self.last_data_frame = Some(v);
                }
            },
            Frame::Headers(v) => {
                if let Some(continuation) = v.encode(&mut self.hpack, self.buf.get_mut()) {
                    self.next = Some(Next::Continuation(continuation));
                }
            },
            Frame::PushPromise(v) => {
                if let Some(continuation) = v.encode(&mut self.hpack, self.buf.get_mut()) {
                    self.next = Some(Next::Continuation(continuation));
                }
            },
            Frame::Settings(v) => {
                v.encode(self.buf.get_mut());
                trace!("encoded settings; rem={:?}", self.buf.remaining());
            },
            Frame::GoAway(v) => {
                v.encode(self.buf.get_mut());
                trace!("encoded go_away; rem={:?}", self.buf.remaining());
            },
            Frame::Ping(v) => {
                v.encode(self.buf.get_mut());
                trace!("encoded ping; rem={:?}", self.buf.remaining());
            },
            Frame::WindowUpdate(v) => {
                v.encode(self.buf.get_mut());
                trace!("encoded window_update; rem={:?}", self.buf.remaining());
            },

            Frame::Priority(_) => {
                /*
                v.encode(self.buf.get_mut());
                trace!("encoded priority; rem={:?}", self.buf.remaining());
                */
                unimplemented!();
            },
            Frame::Reset(v) => {
                v.encode(self.buf.get_mut());
                trace!("encoded reset; rem={:?}", self.buf.remaining());
            },
        }

        Ok(())
    }

    /// Flush buffered data to the wire
    pub fn flush(&mut self) -> Poll<(), io::Error> {
        trace!("flush");

        loop {
            while !self.is_empty() {
                match self.next {
                    Some(Next::Data(ref mut frame)) => {
                        trace!("  -> queued data frame");
                        let mut buf = Buf::by_ref(&mut self.buf).chain(frame.payload_mut());
                        try_ready!(self.inner.write_buf(&mut buf));
                    },
                    _ => {
                        trace!("  -> not a queued data frame");
                        try_ready!(self.inner.write_buf(&mut self.buf));
                    },
                }
            }

            // Clear internal buffer
            self.buf.set_position(0);
            self.buf.get_mut().clear();

            // The data frame has been written, so unset it
            match self.next.take() {
                Some(Next::Data(frame)) => {
                    self.last_data_frame = Some(frame);
                    debug_assert!(self.is_empty());
                    break;
                },
                Some(Next::Continuation(frame)) => {
                    // Buffer the continuation frame, then try to write again
                    if let Some(continuation) = frame.encode(&mut self.hpack, self.buf.get_mut()) {

                        // We previously had a CONTINUATION, and after encoding
                        // it, we got *another* one? Let's just double check
                        // that at least some progress is being made...
                        if self.buf.get_ref().len() == frame::HEADER_LEN {
                            // If *only* the CONTINUATION frame header was
                            // written, and *no* header fields, we're stuck
                            // in a loop...
                            panic!("CONTINUATION frame write loop; header value too big to encode");
                        }

                        self.next = Some(Next::Continuation(continuation));
                    }
                },
                None => {
                    break;
                }
            }
        }

        trace!("flushing buffer");
        // Flush the upstream
        try_nb!(self.inner.flush());

        Ok(Async::Ready(()))
    }

    /// Close the codec
    pub fn shutdown(&mut self) -> Poll<(), io::Error> {
        try_ready!(self.flush());
        self.inner.shutdown().map_err(Into::into)
    }

    fn has_capacity(&self) -> bool {
        self.next.is_none() && self.buf.get_ref().remaining_mut() >= MIN_BUFFER_CAPACITY
    }

    fn is_empty(&self) -> bool {
        match self.next {
            Some(Next::Data(ref frame)) => !frame.payload().has_remaining(),
            _ => !self.buf.has_remaining(),
        }
    }
}

impl<T, B> FramedWrite<T, B> {
    /// Returns the max frame size that can be sent
    pub fn max_frame_size(&self) -> usize {
        self.max_frame_size as usize
    }

    /// Set the peer's max frame size.
    pub fn set_max_frame_size(&mut self, val: usize) {
        assert!(val <= frame::MAX_MAX_FRAME_SIZE as usize);
        self.max_frame_size = val as FrameSize;
    }

    /// Set the peer's max header table size.
    pub fn set_max_header_table_size(&mut self, val: usize) {
        self.hpack.update_max_size(val);
    }

    /// Retrieve the last data frame that has been sent
    pub fn take_last_data_frame(&mut self) -> Option<frame::Data<B>> {
        self.last_data_frame.take()
    }

    pub fn get_mut(&mut self) -> &mut T {
        &mut self.inner
    }
}

impl<T: io::Read, B> io::Read for FramedWrite<T, B> {
    fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> {
        self.inner.read(dst)
    }
}

impl<T: AsyncRead, B> AsyncRead for FramedWrite<T, B> {
    fn read_buf<B2: BufMut>(&mut self, buf: &mut B2) -> Poll<usize, io::Error>
    where
        Self: Sized,
    {
        self.inner.read_buf(buf)
    }

    unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool {
        self.inner.prepare_uninitialized_buffer(buf)
    }
}

#[cfg(feature = "unstable")]
mod unstable {
    use super::*;

    impl<T, B> FramedWrite<T, B> {
        pub fn get_ref(&self) -> &T {
            &self.inner
        }
    }
}