2017-11-08 14:51:51 +01:00
|
|
|
// Copyright 2017 Parity Technologies (UK) Ltd.
|
|
|
|
//
|
2018-03-07 16:20:55 +01:00
|
|
|
// 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:
|
|
|
|
//
|
2018-03-07 16:20:55 +01:00
|
|
|
// 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.
|
|
|
|
//
|
2018-03-07 16:20:55 +01:00
|
|
|
// 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 + Sink` that produces
|
2017-12-07 12:59:46 +01:00
|
|
|
//! and accepts byte arrays, and implements `AsyncRead` and `AsyncWrite`.
|
2017-12-06 16:24:15 +01:00
|
|
|
//!
|
|
|
|
//! Each call to `write()` will send one packet on the sink. Calls to `read()` will read from
|
|
|
|
//! incoming packets.
|
|
|
|
//!
|
2017-12-07 12:59:46 +01:00
|
|
|
//! > **Note**: Although this crate is hosted in the libp2p repo, it is purely a utility crate and
|
|
|
|
//! > not at all specific to libp2p.
|
2017-11-08 14:51:51 +01:00
|
|
|
|
|
|
|
extern crate bytes;
|
|
|
|
extern crate futures;
|
|
|
|
extern crate tokio_io;
|
|
|
|
|
2018-05-14 15:55:16 +02:00
|
|
|
use bytes::{Buf, IntoBuf};
|
|
|
|
use futures::{Async, AsyncSink, Poll, Sink, Stream};
|
2017-11-08 14:51:51 +01:00
|
|
|
use std::cmp;
|
|
|
|
use std::io::Error as IoError;
|
|
|
|
use std::io::ErrorKind as IoErrorKind;
|
|
|
|
use std::io::{Read, Write};
|
|
|
|
use tokio_io::{AsyncRead, AsyncWrite};
|
|
|
|
|
|
|
|
/// Wraps around a `Stream + Sink` whose items are buffers. Implements `AsyncRead` and `AsyncWrite`.
|
2018-03-07 16:20:55 +01:00
|
|
|
pub struct RwStreamSink<S>
|
|
|
|
where
|
|
|
|
S: Stream,
|
|
|
|
S::Item: IntoBuf,
|
|
|
|
{
|
2017-11-08 14:51:51 +01:00
|
|
|
inner: S,
|
|
|
|
current_item: Option<<S::Item as IntoBuf>::Buf>,
|
|
|
|
}
|
|
|
|
|
2018-03-07 16:20:55 +01:00
|
|
|
impl<S> RwStreamSink<S>
|
|
|
|
where
|
|
|
|
S: Stream,
|
|
|
|
S::Item: IntoBuf,
|
|
|
|
{
|
2017-11-08 14:51:51 +01:00
|
|
|
/// Wraps around `inner`.
|
|
|
|
#[inline]
|
|
|
|
pub fn new(inner: S) -> RwStreamSink<S> {
|
|
|
|
RwStreamSink {
|
|
|
|
inner: inner,
|
|
|
|
current_item: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S> Read for RwStreamSink<S>
|
2018-03-07 16:20:55 +01:00
|
|
|
where
|
|
|
|
S: Stream<Error = IoError>,
|
|
|
|
S::Item: IntoBuf,
|
2017-11-08 14:51:51 +01:00
|
|
|
{
|
|
|
|
fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> {
|
|
|
|
let mut written = 0;
|
|
|
|
|
|
|
|
loop {
|
|
|
|
let need_new_item = if let Some(ref i) = self.current_item {
|
|
|
|
!i.has_remaining()
|
|
|
|
} else {
|
|
|
|
true
|
|
|
|
};
|
|
|
|
|
|
|
|
if need_new_item {
|
2018-11-23 13:54:17 +01:00
|
|
|
loop {
|
|
|
|
self.current_item = match self.inner.poll() {
|
|
|
|
Ok(Async::Ready(None)) => None,
|
|
|
|
Ok(Async::Ready(Some(i))) => {
|
|
|
|
let b = i.into_buf();
|
|
|
|
if !b.has_remaining() {
|
|
|
|
continue // skip over empty items
|
|
|
|
}
|
|
|
|
Some(b)
|
2017-11-08 14:51:51 +01:00
|
|
|
}
|
2018-11-23 13:54:17 +01:00
|
|
|
Ok(Async::NotReady) => {
|
|
|
|
if written == 0 {
|
|
|
|
return Err(IoError::new(IoErrorKind::WouldBlock, "stream not ready"));
|
|
|
|
} else {
|
|
|
|
return Ok(written);
|
|
|
|
}
|
2017-11-08 14:51:51 +01:00
|
|
|
}
|
2018-11-23 13:54:17 +01:00
|
|
|
Err(err) => {
|
|
|
|
if written == 0 {
|
|
|
|
return Err(err);
|
|
|
|
} else {
|
|
|
|
return Ok(written);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
break
|
|
|
|
}
|
2017-11-08 14:51:51 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
let current_item = match self.current_item {
|
|
|
|
Some(ref mut i) => i,
|
|
|
|
None => return Ok(written),
|
|
|
|
};
|
|
|
|
|
|
|
|
let to_copy = cmp::min(buf.len() - written, current_item.remaining());
|
|
|
|
if to_copy == 0 {
|
|
|
|
return Ok(written);
|
|
|
|
}
|
|
|
|
|
2018-03-07 16:20:55 +01:00
|
|
|
current_item
|
|
|
|
.by_ref()
|
|
|
|
.take(to_copy)
|
|
|
|
.copy_to_slice(&mut buf[written..(written + to_copy)]);
|
2017-11-08 14:51:51 +01:00
|
|
|
written += to_copy;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S> AsyncRead for RwStreamSink<S>
|
2018-03-07 16:20:55 +01:00
|
|
|
where
|
|
|
|
S: Stream<Error = IoError>,
|
|
|
|
S::Item: IntoBuf,
|
2017-11-08 14:51:51 +01:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S> Write for RwStreamSink<S>
|
2018-03-07 16:20:55 +01:00
|
|
|
where
|
|
|
|
S: Stream + Sink<SinkError = IoError>,
|
|
|
|
S::SinkItem: for<'r> From<&'r [u8]>,
|
|
|
|
S::Item: IntoBuf,
|
2017-11-08 14:51:51 +01:00
|
|
|
{
|
|
|
|
#[inline]
|
|
|
|
fn write(&mut self, buf: &[u8]) -> Result<usize, IoError> {
|
|
|
|
let len = buf.len();
|
|
|
|
match self.inner.start_send(buf.into())? {
|
|
|
|
AsyncSink::Ready => Ok(len),
|
|
|
|
AsyncSink::NotReady(_) => Err(IoError::new(IoErrorKind::WouldBlock, "not ready")),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn flush(&mut self) -> Result<(), IoError> {
|
2018-06-21 11:57:15 +02:00
|
|
|
match self.inner.poll_complete()? {
|
|
|
|
Async::Ready(()) => Ok(()),
|
|
|
|
Async::NotReady => Err(IoError::new(IoErrorKind::WouldBlock, "not ready"))
|
|
|
|
}
|
2017-11-08 14:51:51 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S> AsyncWrite for RwStreamSink<S>
|
2018-03-07 16:20:55 +01:00
|
|
|
where
|
|
|
|
S: Stream + Sink<SinkError = IoError>,
|
|
|
|
S::SinkItem: for<'r> From<&'r [u8]>,
|
|
|
|
S::Item: IntoBuf,
|
2017-11-08 14:51:51 +01:00
|
|
|
{
|
|
|
|
#[inline]
|
|
|
|
fn shutdown(&mut self) -> Poll<(), IoError> {
|
2018-09-21 10:10:45 +02:00
|
|
|
self.inner.close()
|
2017-11-08 14:51:51 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2018-05-14 15:55:16 +02:00
|
|
|
use RwStreamSink;
|
2017-11-08 14:51:51 +01:00
|
|
|
use bytes::Bytes;
|
|
|
|
use futures::sync::mpsc::channel;
|
2018-05-14 15:55:16 +02:00
|
|
|
use futures::{Future, Poll, Sink, StartSend, Stream};
|
2017-11-08 14:51:51 +01:00
|
|
|
use std::io::Read;
|
|
|
|
|
|
|
|
// This struct merges a stream and a sink and is quite useful for tests.
|
|
|
|
struct Wrapper<St, Si>(St, Si);
|
2018-03-07 16:20:55 +01:00
|
|
|
impl<St, Si> Stream for Wrapper<St, Si>
|
|
|
|
where
|
|
|
|
St: Stream,
|
|
|
|
{
|
2017-11-08 14:51:51 +01:00
|
|
|
type Item = St::Item;
|
|
|
|
type Error = St::Error;
|
|
|
|
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
|
|
|
self.0.poll()
|
|
|
|
}
|
|
|
|
}
|
2018-03-07 16:20:55 +01:00
|
|
|
impl<St, Si> Sink for Wrapper<St, Si>
|
|
|
|
where
|
|
|
|
Si: Sink,
|
|
|
|
{
|
2017-11-08 14:51:51 +01:00
|
|
|
type SinkItem = Si::SinkItem;
|
|
|
|
type SinkError = Si::SinkError;
|
2018-03-07 16:20:55 +01:00
|
|
|
fn start_send(
|
|
|
|
&mut self,
|
|
|
|
item: Self::SinkItem,
|
|
|
|
) -> StartSend<Self::SinkItem, Self::SinkError> {
|
2017-11-08 14:51:51 +01:00
|
|
|
self.1.start_send(item)
|
|
|
|
}
|
|
|
|
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
|
|
|
|
self.1.poll_complete()
|
|
|
|
}
|
2018-09-17 15:01:37 +02:00
|
|
|
fn close(&mut self) -> Poll<(), Self::SinkError> {
|
|
|
|
self.1.close()
|
|
|
|
}
|
2017-11-08 14:51:51 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn basic_reading() {
|
|
|
|
let (tx1, _) = channel::<Vec<u8>>(10);
|
|
|
|
let (tx2, rx2) = channel(10);
|
|
|
|
|
|
|
|
let mut wrapper = RwStreamSink::new(Wrapper(rx2.map_err(|_| panic!()), tx1));
|
|
|
|
|
|
|
|
tx2.send(Bytes::from("hel"))
|
|
|
|
.and_then(|tx| tx.send(Bytes::from("lo wor")))
|
|
|
|
.and_then(|tx| tx.send(Bytes::from("ld")))
|
2018-03-07 16:20:55 +01:00
|
|
|
.wait()
|
|
|
|
.unwrap();
|
2017-11-08 14:51:51 +01:00
|
|
|
|
|
|
|
let mut data1 = [0u8; 5];
|
|
|
|
assert_eq!(wrapper.read(&mut data1).unwrap(), 5);
|
|
|
|
assert_eq!(&data1, b"hello");
|
|
|
|
|
|
|
|
let mut data2 = Vec::new();
|
|
|
|
wrapper.read_to_end(&mut data2).unwrap();
|
|
|
|
assert_eq!(data2, b" world");
|
|
|
|
}
|
|
|
|
}
|