Files
tokio/tokio-net/src/tcp/split.rs
T

98 lines
2.5 KiB
Rust
Raw Normal View History

2019-06-29 14:36:49 +08:00
//! `TcpStream` split support.
//!
2019-08-30 20:46:07 -07:00
//! A `TcpStream` can be split into a `ReadHalf` and a
//! `WriteHalf` with the `TcpStream::split` method. `ReadHalf`
//! implements `AsyncRead` while `WriteHalf` implements `AsyncWrite`.
2019-06-29 14:36:49 +08:00
//!
//! Compared to the generic split of `AsyncRead + AsyncWrite`, this specialized
2019-08-30 20:46:07 -07:00
//! split has no associated overhead and enforces all invariants at the type
//! level.
2019-06-29 14:36:49 +08:00
use super::TcpStream;
2019-08-15 20:37:25 -07:00
use tokio_io::{AsyncRead, AsyncWrite};
2019-06-29 14:36:49 +08:00
use bytes::{Buf, BufMut};
use std::io;
use std::net::Shutdown;
use std::pin::Pin;
use std::task::{Context, Poll};
/// Read half of a `TcpStream`.
#[derive(Debug)]
2019-08-30 20:46:07 -07:00
pub struct ReadHalf<'a>(&'a TcpStream);
2019-06-29 14:36:49 +08:00
/// Write half of a `TcpStream`.
///
/// Note that in the `AsyncWrite` implemenation of `TcpStreamWriteHalf`,
/// `poll_shutdown` actually shuts down the TCP stream in the write direction.
#[derive(Debug)]
2019-08-30 20:46:07 -07:00
pub struct WriteHalf<'a>(&'a TcpStream);
2019-06-29 14:36:49 +08:00
2019-08-30 20:46:07 -07:00
pub(crate) fn split(stream: &mut TcpStream) -> (ReadHalf<'_>, WriteHalf<'_>) {
(ReadHalf(&*stream), WriteHalf(&*stream))
2019-06-29 14:36:49 +08:00
}
2019-08-30 20:46:07 -07:00
impl AsyncRead for ReadHalf<'_> {
2019-06-29 14:36:49 +08:00
unsafe fn prepare_uninitialized_buffer(&self, _: &mut [u8]) -> bool {
false
}
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
self.0.poll_read_priv(cx, buf)
}
fn poll_read_buf<B: BufMut>(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut B,
) -> Poll<io::Result<usize>> {
self.0.poll_read_buf_priv(cx, buf)
}
}
2019-08-30 20:46:07 -07:00
impl AsyncWrite for WriteHalf<'_> {
2019-06-29 14:36:49 +08:00
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
self.0.poll_write_priv(cx, buf)
}
#[inline]
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
// tcp flush is a no-op
Poll::Ready(Ok(()))
}
// `poll_shutdown` on a write half shutdowns the stream in the "write" direction.
fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
self.0.shutdown(Shutdown::Write).into()
}
fn poll_write_buf<B: Buf>(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut B,
) -> Poll<io::Result<usize>> {
self.0.poll_write_buf_priv(cx, buf)
}
}
2019-08-30 20:46:07 -07:00
impl AsRef<TcpStream> for ReadHalf<'_> {
fn as_ref(&self) -> &TcpStream {
self.0
}
}
2019-08-30 20:46:07 -07:00
impl AsRef<TcpStream> for WriteHalf<'_> {
fn as_ref(&self) -> &TcpStream {
self.0
}
}