| 1 | use super::fuse::Fuse; |
| 2 | use super::Encoder; |
| 3 | use bytes::{Buf, BytesMut}; |
| 4 | use futures::io::{AsyncRead, AsyncWrite}; |
| 5 | use futures::{ready, Sink}; |
| 6 | use pin_project::pin_project; |
| 7 | use std::io::{Error, ErrorKind}; |
| 8 | use std::marker::Unpin; |
| 9 | use std::ops::{Deref, DerefMut}; |
| 10 | use std::pin::Pin; |
| 11 | use std::task::{Context, Poll}; |
| 12 | |
| 13 | /// A `Sink` of frames encoded to an `AsyncWrite`. |
| 14 | /// |
| 15 | /// # Example |
| 16 | /// ``` |
| 17 | /// use bytes::Bytes; |
| 18 | /// use futures_codec::{FramedWrite, BytesCodec}; |
| 19 | /// use futures::SinkExt; |
| 20 | /// |
| 21 | /// # futures::executor::block_on(async move { |
| 22 | /// let mut buf = Vec::new(); |
| 23 | /// let mut framed = FramedWrite::new(&mut buf, BytesCodec {}); |
| 24 | /// |
| 25 | /// let bytes = Bytes::from("Hello World!"); |
| 26 | /// framed.send(bytes.clone()).await?; |
| 27 | /// |
| 28 | /// assert_eq!(&buf[..], &bytes[..]); |
| 29 | /// # Ok::<_, std::io::Error>(()) |
| 30 | /// # }).unwrap(); |
| 31 | /// ``` |
| 32 | #[pin_project] |
| 33 | #[derive(Debug)] |
| 34 | pub struct FramedWrite<T, E> { |
| 35 | #[pin] |
| 36 | inner: FramedWrite2<Fuse<T, E>>, |
| 37 | } |
| 38 | |
| 39 | impl<T, E> FramedWrite<T, E> |
| 40 | where |
| 41 | T: AsyncWrite, |
| 42 | E: Encoder, |
| 43 | { |
| 44 | /// Creates a new `FramedWrite` transport with the given `Encoder`. |
| 45 | pub fn new(inner: T, encoder: E) -> Self { |
| 46 | Self { |
| 47 | inner: framed_write_2(Fuse::new(inner, encoder)), |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | /// High-water mark for writes, in bytes |
| 52 | /// |
| 53 | /// The send *high-water mark* prevents the `FramedWrite` |
| 54 | /// from accepting additional messages to send when its |
| 55 | /// buffer exceeds this length, in bytes. Attempts to enqueue |
| 56 | /// additional messages will be deferred until progress is |
| 57 | /// made on the underlying `AsyncWrite`. This applies |
| 58 | /// back-pressure on fast senders and prevents unbounded |
| 59 | /// buffer growth. |
| 60 | /// |
| 61 | /// See [`set_send_high_water_mark()`](#method.set_send_high_water_mark). |
| 62 | pub fn send_high_water_mark(&self) -> usize { |
| 63 | return self.inner.high_water_mark; |
| 64 | } |
| 65 | |
| 66 | /// Sets high-water mark for writes, in bytes |
| 67 | /// |
| 68 | /// The send *high-water mark* prevents the `FramedWrite` |
| 69 | /// from accepting additional messages to send when its |
| 70 | /// buffer exceeds this length, in bytes. Attempts to enqueue |
| 71 | /// additional messages will be deferred until progress is |
| 72 | /// made on the underlying `AsyncWrite`. This applies |
| 73 | /// back-pressure on fast senders and prevents unbounded |
| 74 | /// buffer growth. |
| 75 | /// |
| 76 | /// The default high-water mark is 2^17 bytes. Applications |
| 77 | /// which desire low latency may wish to reduce this value. |
| 78 | /// There is little point to increasing this value beyond |
| 79 | /// your socket's `SO_SNDBUF` size. On linux, this defaults |
| 80 | /// to 212992 bytes but is user-adjustable. |
| 81 | pub fn set_send_high_water_mark(&mut self, hwm: usize) { |
| 82 | self.inner.high_water_mark = hwm; |
| 83 | } |
| 84 | |
| 85 | /// Release the I/O and Encoder |
| 86 | pub fn release(self) -> (T, E) { |
| 87 | let fuse = self.inner.release(); |
| 88 | (fuse.t, fuse.u) |
| 89 | } |
| 90 | |
| 91 | /// Consumes the `FramedWrite`, returning its underlying I/O stream. |
| 92 | /// |
| 93 | /// Note that care should be taken to not tamper with the underlying stream |
| 94 | /// of data coming in as it may corrupt the stream of frames otherwise |
| 95 | /// being worked with. |
| 96 | pub fn into_inner(self) -> T { |
| 97 | self.release().0 |
| 98 | } |
| 99 | |
| 100 | /// Returns a reference to the underlying encoder. |
| 101 | /// |
| 102 | /// Note that care should be taken to not tamper with the underlying encoder |
| 103 | /// as it may corrupt the stream of frames otherwise being worked with. |
| 104 | pub fn encoder(&self) -> &E { |
| 105 | &self.inner.u |
| 106 | } |
| 107 | |
| 108 | /// Returns a mutable reference to the underlying encoder. |
| 109 | /// |
| 110 | /// Note that care should be taken to not tamper with the underlying encoder |
| 111 | /// as it may corrupt the stream of frames otherwise being worked with. |
| 112 | pub fn encoder_mut(&mut self) -> &mut E { |
| 113 | &mut self.inner.u |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | impl<T, E> Sink<E::Item> for FramedWrite<T, E> |
| 118 | where |
| 119 | T: AsyncWrite + Unpin, |
| 120 | E: Encoder, |
| 121 | { |
| 122 | type Error = E::Error; |
| 123 | |
| 124 | fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { |
| 125 | self.project().inner.poll_ready(cx) |
| 126 | } |
| 127 | fn start_send(self: Pin<&mut Self>, item: E::Item) -> Result<(), Self::Error> { |
| 128 | self.project().inner.start_send(item) |
| 129 | } |
| 130 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { |
| 131 | self.project().inner.poll_flush(cx) |
| 132 | } |
| 133 | fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { |
| 134 | self.project().inner.poll_close(cx) |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | impl<T, E> Deref for FramedWrite<T, E> { |
| 139 | type Target = T; |
| 140 | |
| 141 | fn deref(&self) -> &T { |
| 142 | &self.inner |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | impl<T, E> DerefMut for FramedWrite<T, E> { |
| 147 | fn deref_mut(&mut self) -> &mut T { |
| 148 | &mut self.inner |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | #[pin_project] |
| 153 | #[derive(Debug)] |
| 154 | pub struct FramedWrite2<T> { |
| 155 | #[pin] |
| 156 | pub inner: T, |
| 157 | pub high_water_mark: usize, |
| 158 | buffer: BytesMut, |
| 159 | } |
| 160 | |
| 161 | impl<T> Deref for FramedWrite2<T> { |
| 162 | type Target = T; |
| 163 | |
| 164 | fn deref(&self) -> &T { |
| 165 | &self.inner |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | impl<T> DerefMut for FramedWrite2<T> { |
| 170 | fn deref_mut(&mut self) -> &mut T { |
| 171 | &mut self.inner |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | // 2^17 bytes, which is slightly over 60% of the default |
| 176 | // TCP send buffer size (SO_SNDBUF) |
| 177 | const DEFAULT_SEND_HIGH_WATER_MARK: usize = 131072; |
| 178 | |
| 179 | pub fn framed_write_2<T>(inner: T) -> FramedWrite2<T> { |
| 180 | FramedWrite2 { |
| 181 | inner, |
| 182 | high_water_mark: DEFAULT_SEND_HIGH_WATER_MARK, |
| 183 | buffer: BytesMut::with_capacity(1028 * 8), |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | impl<T: AsyncRead + Unpin> AsyncRead for FramedWrite2<T> { |
| 188 | fn poll_read( |
| 189 | self: Pin<&mut Self>, |
| 190 | cx: &mut Context<'_>, |
| 191 | buf: &mut [u8], |
| 192 | ) -> Poll<Result<usize, Error>> { |
| 193 | self.project().inner.poll_read(cx, buf) |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | impl<T> Sink<T::Item> for FramedWrite2<T> |
| 198 | where |
| 199 | T: AsyncWrite + Encoder + Unpin, |
| 200 | { |
| 201 | type Error = T::Error; |
| 202 | |
| 203 | fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { |
| 204 | let this = &mut *self; |
| 205 | while this.buffer.len() >= this.high_water_mark { |
| 206 | let num_write = ready!(Pin::new(&mut this.inner).poll_write(cx, &this.buffer))?; |
| 207 | |
| 208 | if num_write == 0 { |
| 209 | return Poll::Ready(Err(err_eof().into())); |
| 210 | } |
| 211 | |
| 212 | this.buffer.advance(num_write); |
| 213 | } |
| 214 | |
| 215 | Poll::Ready(Ok(())) |
| 216 | } |
| 217 | fn start_send(mut self: Pin<&mut Self>, item: T::Item) -> Result<(), Self::Error> { |
| 218 | let this = &mut *self; |
| 219 | this.inner.encode(item, &mut this.buffer) |
| 220 | } |
| 221 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { |
| 222 | let mut this = self.project(); |
| 223 | |
| 224 | while !this.buffer.is_empty() { |
| 225 | let num_write = ready!(Pin::new(&mut this.inner).poll_write(cx, &this.buffer))?; |
| 226 | |
| 227 | if num_write == 0 { |
| 228 | return Poll::Ready(Err(err_eof().into())); |
| 229 | } |
| 230 | |
| 231 | this.buffer.advance(num_write); |
| 232 | } |
| 233 | |
| 234 | this.inner.poll_flush(cx).map_err(Into::into) |
| 235 | } |
| 236 | fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { |
| 237 | ready!(self.as_mut().poll_flush(cx))?; |
| 238 | self.project().inner.poll_close(cx).map_err(Into::into) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | impl<T> FramedWrite2<T> { |
| 243 | pub fn release(self) -> T { |
| 244 | self.inner |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | fn err_eof() -> Error { |
| 249 | Error::new(ErrorKind::UnexpectedEof, "End of file") |
| 250 | } |