tokio_io/_tokio_codec/
framed_write.rs

1#![allow(deprecated)]
2
3use std::fmt;
4use std::io::{self, Read};
5
6use super::framed::Fuse;
7use codec::{Decoder, Encoder};
8use {AsyncRead, AsyncWrite};
9
10use bytes::BytesMut;
11use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream};
12
13/// A `Sink` of frames encoded to an `AsyncWrite`.
14pub struct FramedWrite<T, E> {
15    inner: FramedWrite2<Fuse<T, E>>,
16}
17
18pub struct FramedWrite2<T> {
19    inner: T,
20    buffer: BytesMut,
21}
22
23const INITIAL_CAPACITY: usize = 8 * 1024;
24const BACKPRESSURE_BOUNDARY: usize = INITIAL_CAPACITY;
25
26impl<T, E> FramedWrite<T, E>
27where
28    T: AsyncWrite,
29    E: Encoder,
30{
31    /// Creates a new `FramedWrite` with the given `encoder`.
32    pub fn new(inner: T, encoder: E) -> FramedWrite<T, E> {
33        FramedWrite {
34            inner: framed_write2(Fuse(inner, encoder)),
35        }
36    }
37}
38
39impl<T, E> FramedWrite<T, E> {
40    /// Returns a reference to the underlying I/O stream wrapped by
41    /// `FramedWrite`.
42    ///
43    /// Note that care should be taken to not tamper with the underlying stream
44    /// of data coming in as it may corrupt the stream of frames otherwise
45    /// being worked with.
46    pub fn get_ref(&self) -> &T {
47        &self.inner.inner.0
48    }
49
50    /// Returns a mutable reference to the underlying I/O stream wrapped by
51    /// `FramedWrite`.
52    ///
53    /// Note that care should be taken to not tamper with the underlying stream
54    /// of data coming in as it may corrupt the stream of frames otherwise
55    /// being worked with.
56    pub fn get_mut(&mut self) -> &mut T {
57        &mut self.inner.inner.0
58    }
59
60    /// Consumes the `FramedWrite`, returning its underlying I/O stream.
61    ///
62    /// Note that care should be taken to not tamper with the underlying stream
63    /// of data coming in as it may corrupt the stream of frames otherwise
64    /// being worked with.
65    pub fn into_inner(self) -> T {
66        self.inner.inner.0
67    }
68
69    /// Returns a reference to the underlying decoder.
70    pub fn encoder(&self) -> &E {
71        &self.inner.inner.1
72    }
73
74    /// Returns a mutable reference to the underlying decoder.
75    pub fn encoder_mut(&mut self) -> &mut E {
76        &mut self.inner.inner.1
77    }
78}
79
80impl<T, E> Sink for FramedWrite<T, E>
81where
82    T: AsyncWrite,
83    E: Encoder,
84{
85    type SinkItem = E::Item;
86    type SinkError = E::Error;
87
88    fn start_send(&mut self, item: E::Item) -> StartSend<E::Item, E::Error> {
89        self.inner.start_send(item)
90    }
91
92    fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
93        self.inner.poll_complete()
94    }
95
96    fn close(&mut self) -> Poll<(), Self::SinkError> {
97        Ok(self.inner.close()?)
98    }
99}
100
101impl<T, D> Stream for FramedWrite<T, D>
102where
103    T: Stream,
104{
105    type Item = T::Item;
106    type Error = T::Error;
107
108    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
109        self.inner.inner.0.poll()
110    }
111}
112
113impl<T, U> fmt::Debug for FramedWrite<T, U>
114where
115    T: fmt::Debug,
116    U: fmt::Debug,
117{
118    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
119        f.debug_struct("FramedWrite")
120            .field("inner", &self.inner.get_ref().0)
121            .field("encoder", &self.inner.get_ref().1)
122            .field("buffer", &self.inner.buffer)
123            .finish()
124    }
125}
126
127// ===== impl FramedWrite2 =====
128
129pub fn framed_write2<T>(inner: T) -> FramedWrite2<T> {
130    FramedWrite2 {
131        inner: inner,
132        buffer: BytesMut::with_capacity(INITIAL_CAPACITY),
133    }
134}
135
136pub fn framed_write2_with_buffer<T>(inner: T, mut buf: BytesMut) -> FramedWrite2<T> {
137    if buf.capacity() < INITIAL_CAPACITY {
138        let bytes_to_reserve = INITIAL_CAPACITY - buf.capacity();
139        buf.reserve(bytes_to_reserve);
140    }
141    FramedWrite2 {
142        inner: inner,
143        buffer: buf,
144    }
145}
146
147impl<T> FramedWrite2<T> {
148    pub fn get_ref(&self) -> &T {
149        &self.inner
150    }
151
152    pub fn into_inner(self) -> T {
153        self.inner
154    }
155
156    pub fn into_parts(self) -> (T, BytesMut) {
157        (self.inner, self.buffer)
158    }
159
160    pub fn get_mut(&mut self) -> &mut T {
161        &mut self.inner
162    }
163}
164
165impl<T> Sink for FramedWrite2<T>
166where
167    T: AsyncWrite + Encoder,
168{
169    type SinkItem = T::Item;
170    type SinkError = T::Error;
171
172    fn start_send(&mut self, item: T::Item) -> StartSend<T::Item, T::Error> {
173        // If the buffer is already over 8KiB, then attempt to flush it. If after flushing it's
174        // *still* over 8KiB, then apply backpressure (reject the send).
175        if self.buffer.len() >= BACKPRESSURE_BOUNDARY {
176            self.poll_complete()?;
177
178            if self.buffer.len() >= BACKPRESSURE_BOUNDARY {
179                return Ok(AsyncSink::NotReady(item));
180            }
181        }
182
183        self.inner.encode(item, &mut self.buffer)?;
184
185        Ok(AsyncSink::Ready)
186    }
187
188    fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
189        trace!("flushing framed transport");
190
191        while !self.buffer.is_empty() {
192            trace!("writing; remaining={}", self.buffer.len());
193
194            let n = try_ready!(self.inner.poll_write(&self.buffer));
195
196            if n == 0 {
197                return Err(io::Error::new(
198                    io::ErrorKind::WriteZero,
199                    "failed to \
200                     write frame to transport",
201                )
202                .into());
203            }
204
205            // TODO: Add a way to `bytes` to do this w/o returning the drained
206            // data.
207            let _ = self.buffer.split_to(n);
208        }
209
210        // Try flushing the underlying IO
211        try_ready!(self.inner.poll_flush());
212
213        trace!("framed transport flushed");
214        return Ok(Async::Ready(()));
215    }
216
217    fn close(&mut self) -> Poll<(), Self::SinkError> {
218        try_ready!(self.poll_complete());
219        Ok(self.inner.shutdown()?)
220    }
221}
222
223impl<T: Decoder> Decoder for FramedWrite2<T> {
224    type Item = T::Item;
225    type Error = T::Error;
226
227    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<T::Item>, T::Error> {
228        self.inner.decode(src)
229    }
230
231    fn decode_eof(&mut self, src: &mut BytesMut) -> Result<Option<T::Item>, T::Error> {
232        self.inner.decode_eof(src)
233    }
234}
235
236impl<T: Read> Read for FramedWrite2<T> {
237    fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> {
238        self.inner.read(dst)
239    }
240}
241
242impl<T: AsyncRead> AsyncRead for FramedWrite2<T> {
243    unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool {
244        self.inner.prepare_uninitialized_buffer(buf)
245    }
246}