| 1 | use super::fuse::Fuse; |
| 2 | use super::Decoder; |
| 3 | |
| 4 | use bytes::BytesMut; |
| 5 | use futures::io::AsyncRead; |
| 6 | use futures::{ready, Sink, Stream, TryStreamExt}; |
| 7 | use pin_project::pin_project; |
| 8 | use std::io; |
| 9 | use std::marker::Unpin; |
| 10 | use std::ops::{Deref, DerefMut}; |
| 11 | use std::pin::Pin; |
| 12 | use std::task::{Context, Poll}; |
| 13 | |
| 14 | /// A `Stream` of messages decoded from an `AsyncRead`. |
| 15 | /// |
| 16 | /// # Example |
| 17 | /// ``` |
| 18 | /// use futures_codec::{BytesCodec, FramedRead}; |
| 19 | /// use futures::TryStreamExt; |
| 20 | /// use bytes::{Bytes}; |
| 21 | /// |
| 22 | /// let buf = [3u8; 3]; |
| 23 | /// let mut framed = FramedRead::new(&buf[..], BytesCodec); |
| 24 | /// |
| 25 | /// # futures::executor::block_on(async move { |
| 26 | /// if let Some(bytes) = framed.try_next().await? { |
| 27 | /// assert_eq!(bytes, Bytes::copy_from_slice(&buf[..])); |
| 28 | /// } |
| 29 | /// # Ok::<_, std::io::Error>(()) |
| 30 | /// # }).unwrap(); |
| 31 | /// ``` |
| 32 | #[derive(Debug)] |
| 33 | pub struct FramedRead<T, D> { |
| 34 | inner: FramedRead2<Fuse<T, D>>, |
| 35 | } |
| 36 | |
| 37 | impl<T, D> Deref for FramedRead<T, D> { |
| 38 | type Target = T; |
| 39 | |
| 40 | fn deref(&self) -> &T { |
| 41 | &self.inner |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | impl<T, D> DerefMut for FramedRead<T, D> { |
| 46 | fn deref_mut(&mut self) -> &mut T { |
| 47 | &mut self.inner |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | impl<T, D> FramedRead<T, D> |
| 52 | where |
| 53 | T: AsyncRead, |
| 54 | D: Decoder, |
| 55 | { |
| 56 | /// Creates a new `FramedRead` transport with the given `Decoder`. |
| 57 | pub fn new(inner: T, decoder: D) -> Self { |
| 58 | Self { |
| 59 | inner: framed_read_2(Fuse::new(inner, decoder)), |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /// Release the I/O and Decoder |
| 64 | pub fn release(self: Self) -> (T, D) { |
| 65 | let fuse = self.inner.release(); |
| 66 | (fuse.t, fuse.u) |
| 67 | } |
| 68 | |
| 69 | /// Consumes the `FramedRead`, returning its underlying I/O stream. |
| 70 | /// |
| 71 | /// Note that care should be taken to not tamper with the underlying stream |
| 72 | /// of data coming in as it may corrupt the stream of frames otherwise |
| 73 | /// being worked with. |
| 74 | pub fn into_inner(self) -> T { |
| 75 | self.release().0 |
| 76 | } |
| 77 | |
| 78 | /// Returns a reference to the underlying decoder. |
| 79 | /// |
| 80 | /// Note that care should be taken to not tamper with the underlying decoder |
| 81 | /// as it may corrupt the stream of frames otherwise being worked with. |
| 82 | pub fn decoder(&self) -> &D { |
| 83 | &self.inner.u |
| 84 | } |
| 85 | |
| 86 | /// Returns a mutable reference to the underlying decoder. |
| 87 | /// |
| 88 | /// Note that care should be taken to not tamper with the underlying decoder |
| 89 | /// as it may corrupt the stream of frames otherwise being worked with. |
| 90 | pub fn decoder_mut(&mut self) -> &mut D { |
| 91 | &mut self.inner.u |
| 92 | } |
| 93 | |
| 94 | /// Returns a reference to the read buffer. |
| 95 | pub fn read_buffer(&self) -> &BytesMut { |
| 96 | &self.inner.buffer |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | impl<T, D> Stream for FramedRead<T, D> |
| 101 | where |
| 102 | T: AsyncRead + Unpin, |
| 103 | D: Decoder, |
| 104 | { |
| 105 | type Item = Result<D::Item, D::Error>; |
| 106 | |
| 107 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 108 | self.inner.try_poll_next_unpin(cx) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | #[pin_project] |
| 113 | #[derive(Debug)] |
| 114 | pub struct FramedRead2<T> { |
| 115 | #[pin] |
| 116 | inner: T, |
| 117 | buffer: BytesMut, |
| 118 | } |
| 119 | |
| 120 | impl<T> Deref for FramedRead2<T> { |
| 121 | type Target = T; |
| 122 | |
| 123 | fn deref(&self) -> &T { |
| 124 | &self.inner |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | impl<T> DerefMut for FramedRead2<T> { |
| 129 | fn deref_mut(&mut self) -> &mut T { |
| 130 | &mut self.inner |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | const INITIAL_CAPACITY: usize = 8 * 1024; |
| 135 | |
| 136 | pub fn framed_read_2<T>(inner: T) -> FramedRead2<T> { |
| 137 | FramedRead2 { |
| 138 | inner, |
| 139 | buffer: BytesMut::with_capacity(INITIAL_CAPACITY), |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | impl<T> Stream for FramedRead2<T> |
| 144 | where |
| 145 | T: AsyncRead + Decoder + Unpin, |
| 146 | { |
| 147 | type Item = Result<T::Item, T::Error>; |
| 148 | |
| 149 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 150 | let this = &mut *self; |
| 151 | |
| 152 | if let Some(item) = this.inner.decode(&mut this.buffer)? { |
| 153 | return Poll::Ready(Some(Ok(item))); |
| 154 | } |
| 155 | |
| 156 | let mut buf = [0u8; INITIAL_CAPACITY]; |
| 157 | |
| 158 | loop { |
| 159 | let n = ready!(Pin::new(&mut this.inner).poll_read(cx, &mut buf))?; |
| 160 | this.buffer.extend_from_slice(&buf[..n]); |
| 161 | |
| 162 | let ended = n == 0; |
| 163 | |
| 164 | match this.inner.decode(&mut this.buffer)? { |
| 165 | Some(item) => return Poll::Ready(Some(Ok(item))), |
| 166 | None if ended => { |
| 167 | if this.buffer.is_empty() { |
| 168 | return Poll::Ready(None); |
| 169 | } else { |
| 170 | match this.inner.decode_eof(&mut this.buffer)? { |
| 171 | Some(item) => return Poll::Ready(Some(Ok(item))), |
| 172 | None if this.buffer.is_empty() => return Poll::Ready(None), |
| 173 | None => { |
| 174 | return Poll::Ready(Some(Err(io::Error::new( |
| 175 | io::ErrorKind::UnexpectedEof, |
| 176 | "bytes remaining in stream", |
| 177 | ) |
| 178 | .into()))); |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | _ => continue, |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | impl<T, I> Sink<I> for FramedRead2<T> |
| 190 | where |
| 191 | T: Sink<I> + Unpin, |
| 192 | { |
| 193 | type Error = T::Error; |
| 194 | |
| 195 | fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { |
| 196 | self.project().inner.poll_ready(cx) |
| 197 | } |
| 198 | fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> { |
| 199 | self.project().inner.start_send(item) |
| 200 | } |
| 201 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { |
| 202 | self.project().inner.poll_flush(cx) |
| 203 | } |
| 204 | fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { |
| 205 | self.project().inner.poll_close(cx) |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | impl<T> FramedRead2<T> { |
| 210 | pub fn release(self: Self) -> T { |
| 211 | self.inner |
| 212 | } |
| 213 | |
| 214 | pub fn buffer(&self) -> &BytesMut { |
| 215 | &self.buffer |
| 216 | } |
| 217 | } |