use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use crate::relay::{RelayTunnel, MAX_RELAY_PAYLOAD};
pub struct RelayTunnelStream {
tunnel: RelayTunnel,
read_carry: Vec<u8>,
read_pos: usize,
}
impl RelayTunnelStream {
pub fn new(tunnel: RelayTunnel) -> Self {
RelayTunnelStream {
tunnel,
read_carry: Vec::new(),
read_pos: 0,
}
}
}
impl AsyncRead for RelayTunnelStream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let this = self.get_mut();
if this.read_pos >= this.read_carry.len() {
match this.tunnel.poll_recv(cx) {
Poll::Ready(Some(payload)) => {
this.read_carry = payload;
this.read_pos = 0;
}
Poll::Ready(None) => return Poll::Ready(Ok(())),
Poll::Pending => return Poll::Pending,
}
}
let remaining = &this.read_carry[this.read_pos..];
let n = remaining.len().min(buf.remaining());
buf.put_slice(&remaining[..n]);
this.read_pos += n;
Poll::Ready(Ok(()))
}
}
impl AsyncWrite for RelayTunnelStream {
fn poll_write(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
let n = buf.len().min(MAX_RELAY_PAYLOAD);
match self.tunnel.send(buf[..n].to_vec()) {
Ok(()) => Poll::Ready(Ok(n)),
Err(e) => Poll::Ready(Err(io::Error::new(io::ErrorKind::BrokenPipe, e))),
}
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}