1 use bytes::Bytes; 2 use futures_sink::Sink; 3 use pin_project_lite::pin_project; 4 use std::pin::Pin; 5 use std::task::{Context, Poll}; 6 7 pin_project! { 8 /// A helper that wraps a [`Sink`]`<`[`Bytes`]`>` and converts it into a 9 /// [`Sink`]`<&'a [u8]>` by copying each byte slice into an owned [`Bytes`]. 10 /// 11 /// See the documentation for [`SinkWriter`] for an example. 12 /// 13 /// [`Bytes`]: bytes::Bytes 14 /// [`SinkWriter`]: crate::io::SinkWriter 15 /// [`Sink`]: futures_sink::Sink 16 #[derive(Debug)] 17 pub struct CopyToBytes<S> { 18 #[pin] 19 inner: S, 20 } 21 } 22 23 impl<S> CopyToBytes<S> { 24 /// Creates a new [`CopyToBytes`]. new(inner: S) -> Self25 pub fn new(inner: S) -> Self { 26 Self { inner } 27 } 28 29 /// Gets a reference to the underlying sink. get_ref(&self) -> &S30 pub fn get_ref(&self) -> &S { 31 &self.inner 32 } 33 34 /// Gets a mutable reference to the underlying sink. get_mut(&mut self) -> &mut S35 pub fn get_mut(&mut self) -> &mut S { 36 &mut self.inner 37 } 38 39 /// Consumes this [`CopyToBytes`], returning the underlying sink. into_inner(self) -> S40 pub fn into_inner(self) -> S { 41 self.inner 42 } 43 } 44 45 impl<'a, S> Sink<&'a [u8]> for CopyToBytes<S> 46 where 47 S: Sink<Bytes>, 48 { 49 type Error = S::Error; 50 poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>51 fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { 52 self.project().inner.poll_ready(cx) 53 } 54 start_send(self: Pin<&mut Self>, item: &'a [u8]) -> Result<(), Self::Error>55 fn start_send(self: Pin<&mut Self>, item: &'a [u8]) -> Result<(), Self::Error> { 56 self.project() 57 .inner 58 .start_send(Bytes::copy_from_slice(item)) 59 } 60 poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>61 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { 62 self.project().inner.poll_flush(cx) 63 } 64 poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>65 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { 66 self.project().inner.poll_close(cx) 67 } 68 } 69