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
//! The `Framed` type for `futures::io::{AsyncRead, AsyncWrite}` streams

use std::{
    error::Error,
    fmt::{
        self,
        Display,
    },
    io,
    pin::Pin,
};

use bytes::{
    buf::UninitSlice,
    Buf,
    BufMut,
    BytesMut,
};

use futures::{
    io::{
        AsyncRead,
        AsyncWrite,
    },
    prelude::*,
    ready,
    task::{
        Context,
        Poll,
    },
};

use super::*;

/// A wrapper around a byte stream that uses an `Encode + Decode` type to
/// produce a `Sink + Stream`
pub struct Framed<S, C> {
    stream: S,
    codec: C,
    read_buf: BytesMut,
    write_buf: BytesMut,
}

impl<S, C: Encode + Decode> Framed<S, C> {
    /// Create a new framed stream from a byte stream and a codec.
    pub fn new(stream: S, codec: C) -> Self {
        Framed {
            stream,
            codec,
            read_buf: BytesMut::default(),
            write_buf: BytesMut::default(),
        }
    }
}

/// Errors arising from reading a frame
#[derive(Debug)]
pub enum ReadFrameError<E> {
    /// There was an error in the underlying stream
    Io(io::Error),
    /// There was an error decoding the frame
    Decode(E),
}

impl<E: Error + Send + Sync + 'static> From<ReadFrameError<E>> for io::Error {
    fn from(other: ReadFrameError<E>) -> io::Error {
        match other {
            ReadFrameError::Decode(err) => io::Error::new(io::ErrorKind::InvalidData, err),
            ReadFrameError::Io(err) => err,
        }
    }
}

impl<E: Display> Display for ReadFrameError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ReadFrameError::Io(e) => write!(f, "error reading from stream: {}", e),
            ReadFrameError::Decode(e) => write!(f, "error decoding frame: {}", e),
        }
    }
}

impl<E> Error for ReadFrameError<E>
where
    E: Error + 'static,
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            ReadFrameError::Io(ref e) => Some(e),
            ReadFrameError::Decode(ref e) => Some(e),
        }
    }
}

impl<S, C> Stream for Framed<S, C>
where
    C: Decode,
    S: AsyncRead,
{
    type Item = Result<C::Item, ReadFrameError<C::Error>>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let (mut stream, codec, read_buf) = unsafe {
            let this = self.get_unchecked_mut();
            (
                Pin::new_unchecked(&mut this.stream),
                &mut this.codec,
                &mut this.read_buf,
            )
        };
        loop {
            let empty = read_buf.is_empty();
            if !empty {
                let (consumed, decode_res) = codec.decode(read_buf);
                read_buf.advance(consumed);
                match decode_res {
                    DecodeResult::Ok(value) => {
                        return Poll::Ready(Some(Ok(value)));
                    }
                    DecodeResult::Err(e) => {
                        return Poll::Ready(Some(Err(ReadFrameError::Decode(e))));
                    }
                    DecodeResult::UnexpectedEnd => {}
                }
            }

            // Make sure there's at least one byte available to read into
            read_buf.reserve(1);

            // Safety: the buffer that we're reading into is immediately zeroed
            // without reading it.
            let eof = unsafe {
                let n = {
                    let b = zero_buf(read_buf.bytes_mut());
                    match ready!(stream.as_mut().poll_read(cx, b)).map_err(ReadFrameError::Io) {
                        Err(e) => return Poll::Ready(Some(Err(e))),
                        Ok(n) => n,
                    }
                };

                read_buf.advance_mut(n);

                n == 0
            };

            if eof {
                if empty {
                    return Poll::Ready(None);
                } else {
                    return Poll::Ready(Some(Err(ReadFrameError::Io(
                        io::ErrorKind::UnexpectedEof.into(),
                    ))));
                }
            }
        }
    }
}

/// Errors arising from writing a frame to a stream
#[derive(Debug)]
pub enum WriteFrameError<E> {
    /// An error in the underlying stream
    Io(io::Error),
    /// An error from encoding the frame
    Encode(E),
}

impl<E: Error + Send + Sync + 'static> From<WriteFrameError<E>> for io::Error {
    fn from(other: WriteFrameError<E>) -> io::Error {
        match other {
            WriteFrameError::Encode(err) => io::Error::new(io::ErrorKind::InvalidInput, err),
            WriteFrameError::Io(err) => err,
        }
    }
}

impl<E: Display> Display for WriteFrameError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            WriteFrameError::Io(e) => write!(f, "error writing to stream: {}", e),
            WriteFrameError::Encode(e) => write!(f, "error encoding frame: {}", e),
        }
    }
}

impl<E> Error for WriteFrameError<E>
where
    E: Error + 'static,
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            WriteFrameError::Io(ref e) => Some(e),
            WriteFrameError::Encode(ref e) => Some(e),
        }
    }
}

impl<S, C> Sink<C::Item> for Framed<S, C>
where
    C: Encode,
    C::Error: std::fmt::Debug,
    S: AsyncWrite,
{
    type Error = WriteFrameError<C::Error>;
    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let (buffer, mut stream) = unsafe {
            let this = self.get_unchecked_mut();
            (&mut this.write_buf, Pin::new_unchecked(&mut this.stream))
        };
        loop {
            if buffer.len() == 0 {
                return Poll::Ready(Ok(()));
            }
            let written = ready!(stream
                .as_mut()
                .poll_write(cx, &buffer)
                .map_err(WriteFrameError::Io))?;
            if written == 0 {
                return Poll::Ready(Err(WriteFrameError::Io(io::ErrorKind::WriteZero.into())));
            }
            buffer.advance(written);
        }
    }
    fn start_send(self: Pin<&mut Self>, item: C::Item) -> Result<(), Self::Error> {
        let (buffer, codec) = unsafe {
            let this = self.get_unchecked_mut();
            (&mut this.write_buf, &mut this.codec)
        };
        codec.reset();
        loop {
            let b = zero_buf(buffer.bytes_mut());
            match codec.encode(&item, b) {
                EncodeResult::Ok(len) => {
                    // Safety: We made sure to zero the buffer above, so this is
                    // safe assuming the advance_mut implementation won't
                    // overflow the buffer
                    unsafe { buffer.advance_mut(len) };
                    return Ok(());
                }
                EncodeResult::Err(e) => return Err(WriteFrameError::Encode(e)),
                EncodeResult::Overflow(0) => buffer.reserve(buffer.remaining_mut() * 2),
                EncodeResult::Overflow(new_size) => buffer.reserve(new_size),
            }
        }
    }
    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
        ready!(self.as_mut().poll_ready(cx))?;

        unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().stream) }
            .poll_flush(cx)
            .map_err(WriteFrameError::Io)
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
        ready!(self.as_mut().poll_flush(cx))?;

        unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().stream) }
            .poll_close(cx)
            .map_err(WriteFrameError::Io)
    }
}

fn zero_buf(b: &mut UninitSlice) -> &mut [u8] {
    for i in 0..b.len() {
        b.write_byte(i, 0)
    }
    unsafe { std::mem::transmute(b) }
}

#[cfg(test)]
mod test {
    use std::str::Utf8Error;

    use futures::{
        io::Cursor,
        prelude::*,
    };

    use super::*;

    struct LineCodec;

    impl Encode for LineCodec {
        type Item = String;
        type Error = ();
        fn encode(&mut self, item: &String, buf: &mut [u8]) -> EncodeResult<()> {
            let needed = item.as_bytes().len() + 1;
            if buf.len() < needed {
                return EncodeResult::Overflow(needed);
            }
            buf[..needed - 1].copy_from_slice(item.as_bytes());
            buf[needed - 1] = b'\n';
            Ok(needed).into()
        }
    }

    impl Decode for LineCodec {
        type Item = String;
        type Error = Utf8Error;

        fn decode(&mut self, buf: &mut [u8]) -> (usize, DecodeResult<String, Utf8Error>) {
            let newline = match buf.iter().position(|b| *b == b'\n') {
                Some(idx) => idx,
                None => return (0, DecodeResult::UnexpectedEnd),
            };
            let string_bytes = &buf[..newline];
            (
                newline + 1,
                std::str::from_utf8(string_bytes).map(String::from).into(),
            )
        }
    }

    const SHAKESPEARE: &str = r#"Now is the winter of our discontent
Made glorious summer by this sun of York.
Some are born great, some achieve greatness
And some have greatness thrust upon them.
Friends, Romans, countrymen - lend me your ears!
I come not to praise Caesar, but to bury him.
The evil that men do lives after them
The good is oft interred with their bones.
                    It is a tale
Told by an idiot, full of sound and fury
Signifying nothing.
Ay me! For aught that I could ever read,
Could ever hear by tale or history,
The course of true love never did run smooth.
I have full cause of weeping, but this heart
Shall break into a hundred thousand flaws,
Or ere I'll weep.-O Fool, I shall go mad!
                    Each your doing,
So singular in each particular,
Crowns what you are doing in the present deed,
That all your acts are queens.
"#;

    #[async_std::test]
    async fn test_framed_stream() {
        let reader = Cursor::new(Vec::from(SHAKESPEARE.as_bytes()));
        let mut framed = Framed::new(reader, LineCodec);
        let expected = SHAKESPEARE.lines().map(String::from).collect::<Vec<_>>();
        let mut actual = vec![];
        while let Some(frame) = framed.next().await.transpose().unwrap() {
            actual.push(frame);
        }
        assert_eq!(actual, expected);
    }

    #[async_std::test]
    async fn test_framed_sink() {
        let frames = SHAKESPEARE.lines().map(String::from).collect::<Vec<_>>();
        let mut actual = vec![0u8; SHAKESPEARE.as_bytes().len()];
        {
            let writer = Cursor::new(&mut actual);
            let mut framed = Framed::new(writer, LineCodec);
            for frame in frames {
                framed.send(frame).await.unwrap();
            }
        }
        assert_eq!(std::str::from_utf8(&actual).unwrap(), SHAKESPEARE);
    }
}