Skip to content

Commit 260a42a

Browse files
authored
Merge pull request #36 from olanod/shutdown-socket
Split TCP stream and shutdown on drop
2 parents f191348 + 1cacfc0 commit 260a42a

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/net/tcp_stream.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,16 @@ impl TcpStream {
2626
.map_err(super::tcp_listener::to_io_err)?;
2727
Ok(format!("{addr:?}"))
2828
}
29+
30+
pub fn split(&self) -> (ReadHalf<'_>, WriteHalf<'_>) {
31+
(ReadHalf(self), WriteHalf(self))
32+
}
33+
}
34+
35+
impl Drop for TcpStream {
36+
fn drop(&mut self) {
37+
let _ = self.socket.shutdown(wasi::sockets::tcp::ShutdownType::Both);
38+
}
2939
}
3040

3141
impl AsyncRead for TcpStream {
@@ -80,6 +90,42 @@ impl AsyncWrite for &TcpStream {
8090
}
8191
}
8292

93+
pub struct ReadHalf<'a>(&'a TcpStream);
94+
impl<'a> AsyncRead for ReadHalf<'a> {
95+
async fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
96+
self.0.read(buf).await
97+
}
98+
}
99+
100+
impl<'a> Drop for ReadHalf<'a> {
101+
fn drop(&mut self) {
102+
let _ = self
103+
.0
104+
.socket
105+
.shutdown(wasi::sockets::tcp::ShutdownType::Receive);
106+
}
107+
}
108+
109+
pub struct WriteHalf<'a>(&'a TcpStream);
110+
impl<'a> AsyncWrite for WriteHalf<'a> {
111+
async fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
112+
self.0.write(buf).await
113+
}
114+
115+
async fn flush(&mut self) -> io::Result<()> {
116+
self.0.flush().await
117+
}
118+
}
119+
120+
impl<'a> Drop for WriteHalf<'a> {
121+
fn drop(&mut self) {
122+
let _ = self
123+
.0
124+
.socket
125+
.shutdown(wasi::sockets::tcp::ShutdownType::Send);
126+
}
127+
}
128+
83129
fn to_io_err(err: StreamError) -> std::io::Error {
84130
match err {
85131
StreamError::LastOperationFailed(err) => Error::other(err.to_debug_string()),

0 commit comments

Comments
 (0)