213 lines
7.4 KiB
Rust
Raw Normal View History

2017-11-08 14:51:51 +01:00
// Copyright 2017 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
2017-11-08 14:51:51 +01:00
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
2017-11-08 14:51:51 +01:00
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
2017-11-08 14:51:51 +01:00
// DEALINGS IN THE SOFTWARE.
//! This crate provides the [`RwStreamSink`] type. It wraps around a [`Stream`]
//! and [`Sink`] that produces and accepts byte arrays, and implements
//! [`AsyncRead`] and [`AsyncWrite`].
2017-12-06 16:24:15 +01:00
//!
//! Each call to [`AsyncWrite::poll_write`] will send one packet to the sink.
//! Calls to [`AsyncRead::read`] will read from the stream's incoming packets.
2017-11-08 14:51:51 +01:00
use bytes::{IntoBuf, Buf};
use futures::{prelude::*, ready};
use std::{io, pin::Pin, task::{Context, Poll}};
2017-11-08 14:51:51 +01:00
/// Wraps a [`Stream`] and [`Sink`] whose items are buffers.
/// Implements [`AsyncRead`] and [`AsyncWrite`].
pub struct RwStreamSink<S>
where
S: TryStream,
<S as TryStream>::Ok: IntoBuf
{
2017-11-08 14:51:51 +01:00
inner: S,
current_item: Option<<<S as TryStream>::Ok as IntoBuf>::Buf>
2017-11-08 14:51:51 +01:00
}
impl<S> RwStreamSink<S>
where
S: TryStream,
<S as TryStream>::Ok: IntoBuf
{
2017-11-08 14:51:51 +01:00
/// Wraps around `inner`.
pub fn new(inner: S) -> Self {
2019-01-30 15:41:54 +01:00
RwStreamSink { inner, current_item: None }
2017-11-08 14:51:51 +01:00
}
}
impl<S> AsyncRead for RwStreamSink<S>
where
S: TryStream<Error = io::Error> + Unpin,
<S as TryStream>::Ok: IntoBuf
2017-11-08 14:51:51 +01:00
{
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<io::Result<usize>> {
// Grab the item to copy from.
let item_to_copy = loop {
if let Some(ref mut i) = self.current_item {
if i.has_remaining() {
break i
}
2017-11-08 14:51:51 +01:00
}
self.current_item = Some(match ready!(self.inner.try_poll_next_unpin(cx)) {
Some(Ok(i)) => i.into_buf(),
Some(Err(e)) => return Poll::Ready(Err(e)),
None => return Poll::Ready(Ok(0)) // EOF
});
};
// Copy it!
debug_assert!(item_to_copy.has_remaining());
let to_copy = std::cmp::min(buf.len(), item_to_copy.remaining());
item_to_copy.take(to_copy).copy_to_slice(&mut buf[.. to_copy]);
Poll::Ready(Ok(to_copy))
2017-11-08 14:51:51 +01:00
}
}
impl<S> AsyncWrite for RwStreamSink<S>
where
S: TryStream + Sink<<S as TryStream>::Ok, Error = io::Error> + Unpin,
<S as TryStream>::Ok: IntoBuf + for<'r> From<&'r [u8]>
2017-11-08 14:51:51 +01:00
{
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>> {
ready!(Pin::new(&mut self.inner).poll_ready(cx)?);
let n = buf.len();
if let Err(e) = Pin::new(&mut self.inner).start_send(buf.into()) {
return Poll::Ready(Err(e))
2017-11-08 14:51:51 +01:00
}
Poll::Ready(Ok(n))
2017-11-08 14:51:51 +01:00
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
2017-11-08 14:51:51 +01:00
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_close(cx)
2017-11-08 14:51:51 +01:00
}
}
impl<S> Unpin for RwStreamSink<S>
where
S: TryStream,
<S as TryStream>::Ok: IntoBuf
{}
2017-11-08 14:51:51 +01:00
#[cfg(test)]
mod tests {
use async_std::task;
use bytes::Bytes;
use futures::{channel::mpsc, prelude::*, stream};
use std::{pin::Pin, task::{Context, Poll}};
use super::RwStreamSink;
2017-11-08 14:51:51 +01:00
// This struct merges a stream and a sink and is quite useful for tests.
struct Wrapper<St, Si>(St, Si);
impl<St, Si> Stream for Wrapper<St, Si>
where
St: Stream + Unpin,
Si: Unpin
{
2017-11-08 14:51:51 +01:00
type Item = St::Item;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
self.0.poll_next_unpin(cx)
2017-11-08 14:51:51 +01:00
}
}
impl<St, Si, T> Sink<T> for Wrapper<St, Si>
where
St: Unpin,
Si: Sink<T> + Unpin,
{
type Error = Si::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.1).poll_ready(cx)
2017-11-08 14:51:51 +01:00
}
fn start_send(mut self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
Pin::new(&mut self.1).start_send(item)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.1).poll_flush(cx)
2017-11-08 14:51:51 +01:00
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.1).poll_close(cx)
2018-09-17 15:01:37 +02:00
}
2017-11-08 14:51:51 +01:00
}
#[test]
fn basic_reading() {
let (tx1, _) = mpsc::channel::<Vec<u8>>(10);
let (mut tx2, rx2) = mpsc::channel(10);
2017-11-08 14:51:51 +01:00
let mut wrapper = RwStreamSink::new(Wrapper(rx2.map(Ok), tx1));
2017-11-08 14:51:51 +01:00
task::block_on(async move {
tx2.send(Bytes::from("hel")).await.unwrap();
tx2.send(Bytes::from("lo wor")).await.unwrap();
tx2.send(Bytes::from("ld")).await.unwrap();
tx2.close().await.unwrap();
2017-11-08 14:51:51 +01:00
let mut data = Vec::new();
wrapper.read_to_end(&mut data).await.unwrap();
assert_eq!(data, b"hello world");
})
2017-11-08 14:51:51 +01:00
}
#[test]
fn skip_empty_stream_items() {
let data: Vec<&[u8]> = vec![b"", b"foo", b"", b"bar", b"", b"baz", b""];
let mut rws = RwStreamSink::new(stream::iter(data).map(Ok));
let mut buf = [0; 9];
task::block_on(async move {
assert_eq!(3, rws.read(&mut buf).await.unwrap());
assert_eq!(3, rws.read(&mut buf[3..]).await.unwrap());
assert_eq!(3, rws.read(&mut buf[6..]).await.unwrap());
assert_eq!(0, rws.read(&mut buf).await.unwrap());
assert_eq!(b"foobarbaz", &buf[..])
})
}
#[test]
fn partial_read() {
let data: Vec<&[u8]> = vec![b"hell", b"o world"];
let mut rws = RwStreamSink::new(stream::iter(data).map(Ok));
let mut buf = [0; 3];
task::block_on(async move {
assert_eq!(3, rws.read(&mut buf).await.unwrap());
assert_eq!(b"hel", &buf[..3]);
assert_eq!(0, rws.read(&mut buf[..0]).await.unwrap());
assert_eq!(1, rws.read(&mut buf).await.unwrap());
assert_eq!(b"l", &buf[..1]);
assert_eq!(3, rws.read(&mut buf).await.unwrap());
assert_eq!(b"o w", &buf[..3]);
assert_eq!(0, rws.read(&mut buf[..0]).await.unwrap());
assert_eq!(3, rws.read(&mut buf).await.unwrap());
assert_eq!(b"orl", &buf[..3]);
assert_eq!(1, rws.read(&mut buf).await.unwrap());
assert_eq!(b"d", &buf[..1]);
assert_eq!(0, rws.read(&mut buf).await.unwrap());
})
}
2017-11-08 14:51:51 +01:00
}