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
/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under both the MIT license found in the
 * LICENSE-MIT file in the root directory of this source tree and the Apache
 * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
 * of this source tree.
 */

//! A layered `Decoder` adapter for `Stream` transformations
//!
//! This module implements an adapter to allow a `tokio_io::codec::Decoder` implementation
//! to transform a `Stream` - specifically, decode from a `Stream` of `Bytes` into some
//! structured type.
//!
//! This allows multiple protocols to be layered and composed with operations on `Streams`,
//! rather than restricting all codec operations to `AsyncRead`/`AsyncWrite` operations on
//! an underlying transport.

use bytes_old::{BufMut, Bytes, BytesMut};
use futures::{try_ready, Async, Poll, Stream};
use tokio_io::codec::Decoder;

/// Returns a stream that will yield decoded items that are the result of decoding
/// [Bytes] of the underlying [Stream] by using the provided [Decoder]
pub fn decode<In, Dec>(input: In, decoder: Dec) -> LayeredDecode<In, Dec>
where
    In: Stream<Item = Bytes>,
    Dec: Decoder,
{
    LayeredDecode {
        input,
        decoder,
        // 8KB is a reasonable default
        buf: BytesMut::with_capacity(8 * 1024),
        eof: false,
        is_readable: false,
    }
}

/// Stream returned by the [decode] function
#[derive(Debug)]
pub struct LayeredDecode<In, Dec> {
    input: In,
    decoder: Dec,
    buf: BytesMut,
    eof: bool,
    is_readable: bool,
}

impl<In, Dec> Stream for LayeredDecode<In, Dec>
where
    In: Stream<Item = Bytes>,
    Dec: Decoder,
    Dec::Error: From<In::Error>,
{
    type Item = Dec::Item;
    type Error = Dec::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Dec::Error> {
        // This is adapted from Framed::poll in tokio. This does its own thing
        // because converting the Bytes input stream to an Io object and then
        // running it through Framed is pointless.
        loop {
            if self.is_readable {
                if self.eof {
                    let ret = if self.buf.is_empty() {
                        None
                    } else {
                        self.decoder.decode_eof(&mut self.buf)?
                    };
                    return Ok(Async::Ready(ret));
                }
                if let Some(frame) = self.decoder.decode(&mut self.buf)? {
                    return Ok(Async::Ready(Some(frame)));
                }
                self.is_readable = false;
            }

            assert!(!self.eof);

            match try_ready!(self.input.poll()) {
                Some(v) => {
                    self.buf.reserve(v.len());
                    self.buf.put(v);
                }
                None => self.eof = true,
            }

            self.is_readable = true;
        }
    }
}

impl<In, Dec> LayeredDecode<In, Dec>
where
    In: Stream<Item = Bytes>,
{
    /// Consume this combinator and returned the underlying stream
    #[inline]
    pub fn into_inner(self) -> In {
        // TODO: do we want to check that buf is empty? otherwise we might lose data
        self.input
    }

    /// Returns reference to the underlying stream
    #[inline]
    pub fn get_ref(&self) -> &In {
        &self.input
    }

    /// Returns mutable reference to the underlying stream
    #[inline]
    pub fn get_mut(&mut self) -> &mut In {
        &mut self.input
    }
}

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

    use anyhow::{Error, Result};
    use bytes_old::Bytes;
    use futures::{stream, Stream};

    use super::*;

    #[derive(Default)]
    struct TestDecoder {}

    impl Decoder for TestDecoder {
        type Item = BytesMut;
        type Error = Error;

        fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>> {
            if !buf.is_empty() {
                let expected_len: usize = u8::from_le(buf[0]).into();
                if buf.len() > expected_len {
                    buf.split_to(1);
                    Ok(Some(buf.split_to(expected_len)))
                } else {
                    Ok(None)
                }
            } else {
                Ok(None)
            }
        }
    }

    #[test]
    fn simple() {
        let mut runtime = tokio::runtime::Runtime::new().unwrap();

        let decoder = TestDecoder::default();

        let inp = stream::iter_ok::<_, io::Error>(vec![Bytes::from(&b"\x0Dhello, world!"[..])]);

        let dec = decode(inp, decoder);
        let out = Vec::new();

        let xfer = dec
            .map_err::<(), _>(|err| {
                panic!("bad = {}", err);
            })
            .forward(out);

        let (_, out) = runtime.block_on(xfer).unwrap();
        let out = out
            .into_iter()
            .flat_map(|x| x.as_ref().to_vec())
            .collect::<Vec<_>>();
        assert_eq!(out, b"hello, world!");
    }

    #[test]
    fn large() {
        let mut runtime = tokio::runtime::Runtime::new().unwrap();

        let decoder = TestDecoder::default();

        let inp =
            stream::iter_ok::<_, io::Error>(vec![Bytes::from("\x0Dhello, world!".repeat(5000))]);

        let dec = decode(inp, decoder);
        let out = Vec::new();

        let xfer = dec
            .map_err::<(), _>(|err| {
                panic!("bad = {}", err);
            })
            .forward(out);

        let (_, out) = runtime.block_on(xfer).unwrap();
        let out = out
            .into_iter()
            .flat_map(|x| x.as_ref().to_vec())
            .collect::<Vec<_>>();

        assert_eq!(out, "hello, world!".repeat(5000).as_bytes());
    }

    #[test]
    fn partial() {
        let mut runtime = tokio::runtime::Runtime::new().unwrap();

        let decoder = TestDecoder::default();

        let inp = stream::iter_ok::<_, io::Error>(vec![
            Bytes::from(&b"\x0Dhel"[..]),
            Bytes::from(&b"lo, world!"[..]),
        ]);

        let dec = decode(inp, decoder);
        let out = Vec::new();

        let xfer = dec
            .map_err::<(), _>(|err| {
                panic!("bad = {}", err);
            })
            .forward(out);

        let (_, out) = runtime.block_on(xfer).unwrap();
        let out = out
            .into_iter()
            .flat_map(|x| x.as_ref().to_vec())
            .collect::<Vec<_>>();
        assert_eq!(out, b"hello, world!");
    }
}