1#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
29
30use std::{
31 io::{self, Read},
32 mem,
33 pin::Pin,
34 task::{Context, Poll},
35};
36
37use futures::{prelude::*, ready};
38
39static_assertions::const_assert!(mem::size_of::<usize>() <= mem::size_of::<u64>());
40
41#[pin_project::pin_project]
44pub struct RwStreamSink<S: TryStream> {
45 #[pin]
46 inner: S,
47 current_item: Option<std::io::Cursor<<S as TryStream>::Ok>>,
48}
49
50impl<S: TryStream> RwStreamSink<S> {
51 pub fn new(inner: S) -> Self {
53 RwStreamSink {
54 inner,
55 current_item: None,
56 }
57 }
58}
59
60impl<S> AsyncRead for RwStreamSink<S>
61where
62 S: TryStream<Error = io::Error>,
63 <S as TryStream>::Ok: AsRef<[u8]>,
64{
65 fn poll_read(
66 self: Pin<&mut Self>,
67 cx: &mut Context,
68 buf: &mut [u8],
69 ) -> Poll<io::Result<usize>> {
70 let mut this = self.project();
71
72 let item_to_copy = loop {
74 if let Some(ref mut i) = this.current_item {
75 if i.position() < i.get_ref().as_ref().len() as u64 {
76 break i;
77 }
78 }
79 *this.current_item = Some(match ready!(this.inner.as_mut().try_poll_next(cx)) {
80 Some(Ok(i)) => std::io::Cursor::new(i),
81 Some(Err(e)) => return Poll::Ready(Err(e)),
82 None => return Poll::Ready(Ok(0)), });
84 };
85
86 Poll::Ready(Ok(item_to_copy.read(buf)?))
88 }
89}
90
91impl<S> AsyncWrite for RwStreamSink<S>
92where
93 S: TryStream + Sink<<S as TryStream>::Ok, Error = io::Error>,
94 <S as TryStream>::Ok: for<'r> From<&'r [u8]>,
95{
96 fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>> {
97 let mut this = self.project();
98 ready!(this.inner.as_mut().poll_ready(cx)?);
99 let n = buf.len();
100 if let Err(e) = this.inner.start_send(buf.into()) {
101 return Poll::Ready(Err(e));
102 }
103 Poll::Ready(Ok(n))
104 }
105
106 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
107 let this = self.project();
108 this.inner.poll_flush(cx)
109 }
110
111 fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
112 let this = self.project();
113 this.inner.poll_close(cx)
114 }
115}
116
117#[cfg(test)]
118mod tests {
119 use std::{
120 pin::Pin,
121 task::{Context, Poll},
122 };
123
124 use futures::{channel::mpsc, prelude::*};
125
126 use super::RwStreamSink;
127
128 struct Wrapper<St, Si>(St, Si);
130
131 impl<St, Si> Stream for Wrapper<St, Si>
132 where
133 St: Stream + Unpin,
134 Si: Unpin,
135 {
136 type Item = St::Item;
137
138 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
139 self.0.poll_next_unpin(cx)
140 }
141 }
142
143 impl<St, Si, T> Sink<T> for Wrapper<St, Si>
144 where
145 St: Unpin,
146 Si: Sink<T> + Unpin,
147 {
148 type Error = Si::Error;
149
150 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
151 Pin::new(&mut self.1).poll_ready(cx)
152 }
153
154 fn start_send(mut self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
155 Pin::new(&mut self.1).start_send(item)
156 }
157
158 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
159 Pin::new(&mut self.1).poll_flush(cx)
160 }
161
162 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
163 Pin::new(&mut self.1).poll_close(cx)
164 }
165 }
166
167 #[tokio::test]
168 async fn basic_reading() {
169 let (tx1, _) = mpsc::channel::<Vec<u8>>(10);
170 let (mut tx2, rx2) = mpsc::channel(10);
171
172 let mut wrapper = RwStreamSink::new(Wrapper(rx2.map(Ok), tx1));
173
174 tx2.send(Vec::from("hel")).await.unwrap();
175 tx2.send(Vec::from("lo wor")).await.unwrap();
176 tx2.send(Vec::from("ld")).await.unwrap();
177 tx2.close().await.unwrap();
178
179 let mut data = Vec::new();
180 wrapper.read_to_end(&mut data).await.unwrap();
181 assert_eq!(data, b"hello world");
182 }
183
184 #[tokio::test]
185 async fn skip_empty_stream_items() {
186 let data: Vec<&[u8]> = vec![b"", b"foo", b"", b"bar", b"", b"baz", b""];
187 let mut rws = RwStreamSink::new(stream::iter(data).map(Ok));
188 let mut buf = [0; 9];
189 assert_eq!(3, rws.read(&mut buf).await.unwrap());
190 assert_eq!(3, rws.read(&mut buf[3..]).await.unwrap());
191 assert_eq!(3, rws.read(&mut buf[6..]).await.unwrap());
192 assert_eq!(0, rws.read(&mut buf).await.unwrap());
193 assert_eq!(b"foobarbaz", &buf[..])
194 }
195
196 #[tokio::test]
197 async fn partial_read() {
198 let data: Vec<&[u8]> = vec![b"hell", b"o world"];
199 let mut rws = RwStreamSink::new(stream::iter(data).map(Ok));
200 let mut buf = [0; 3];
201 assert_eq!(3, rws.read(&mut buf).await.unwrap());
202 assert_eq!(b"hel", &buf[..3]);
203 assert_eq!(0, rws.read(&mut buf[..0]).await.unwrap());
204 assert_eq!(1, rws.read(&mut buf).await.unwrap());
205 assert_eq!(b"l", &buf[..1]);
206 assert_eq!(3, rws.read(&mut buf).await.unwrap());
207 assert_eq!(b"o w", &buf[..3]);
208 assert_eq!(0, rws.read(&mut buf[..0]).await.unwrap());
209 assert_eq!(3, rws.read(&mut buf).await.unwrap());
210 assert_eq!(b"orl", &buf[..3]);
211 assert_eq!(1, rws.read(&mut buf).await.unwrap());
212 assert_eq!(b"d", &buf[..1]);
213 assert_eq!(0, rws.read(&mut buf).await.unwrap());
214 }
215}