tokio有BufStream,async-std居然没有,来给它包一包
use async_std:: net::TcpStream;
use async_std::io::{BufWriter,BufReader};
use futures::{AsyncRead,AsyncWrite};
use futures::{
io::{IoSliceMut},
prelude::*,
};
use pin_project_lite::pin_project;
use std::{io, io::Error as IoError, pin::Pin, task::Context, task::Poll};
pin_project! {
struct BufStream
{
#[pin]
reader : BufReader<&'static TcpStream>,
#[pin]
writer: BufWriter<&'static TcpStream>,
_socket: Pin<Box<TcpStream>>,
}
}
impl BufStream{
pub fn new(socket: TcpStream) -> Self {
let pin = Box::pin(socket);
unsafe {
Self{
reader : BufReader::new(std::mem::transmute(&*pin)),
writer: BufWriter::new(std::mem::transmute(&*pin)),
_socket: pin,
}
}
}
}
impl AsyncRead for BufStream {
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize, IoError>> {
self.project().reader.poll_read(cx, buf)
}
fn poll_read_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<io::Result<usize>> {
self.project().reader.poll_read_vectored(cx, bufs)
}
}
impl AsyncWrite for BufStream {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
self.project().writer.poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.project().writer.poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.project().writer.poll_close(cx)
}
}
impl AsyncBufRead for BufStream {
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
self.project().reader.poll_fill_buf(cx)
}
fn consume(self: Pin<&mut Self>, amt: usize) {
self.project().reader.consume(amt)
}
}