sheave_core/handlers/
vec_stream.rs

1use std::{
2    io::Result as IOResult,
3    pin::{
4        Pin,
5        pin
6    },
7    task::{
8        Context,
9        Poll
10    }
11};
12use futures::ready;
13use tokio::io::{
14    AsyncRead,
15    AsyncWrite,
16    ReadBuf
17};
18
19/// The simple stream for std's buffer-like types.
20///
21/// `[u8]` can't write, against `Vec` can't read.
22/// std's buffer-like types can't act as streams which coincide reading and writing.
23/// Therefore this type was prepared for wrapping them.
24/// Mainly, this is expected that is used for testing handlers.
25#[derive(Debug, Default)]
26pub struct VecStream(Vec<u8>);
27
28impl AsyncRead for VecStream {
29    fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<IOResult<()>> {
30        ready!(pin!(self.0.as_slice()).poll_read(cx, buf))?;
31        self.0 = self.0.split_off(buf.filled().len());
32        Poll::Ready(Ok(()))
33    }
34}
35
36impl AsyncWrite for VecStream {
37    fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<IOResult<usize>> {
38        Pin::new(&mut self.0).poll_write(cx, buf)
39    }
40
41    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IOResult<()>> {
42        Pin::new(&mut self.0).poll_flush(cx)
43    }
44
45    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IOResult<()>> {
46        Pin::new(&mut self.0).poll_shutdown(cx)
47    }
48}