Skip to content

Commit 7eb05a6

Browse files
committed
refactor(net): clarify io_util code a bit
1 parent 592649c commit 7eb05a6

File tree

1 file changed

+16
-19
lines changed

1 file changed

+16
-19
lines changed

crates/net/src/websocket/io_util.rs

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,19 @@ impl WebSocket {
2222
}
2323
}
2424

25+
macro_rules! try_in_poll_io {
26+
($expr:expr) => {{
27+
match $expr {
28+
Ok(o) => o,
29+
// WebSocket is closed, nothing more to read or write
30+
Err(WebSocketError::ConnectionClose(event)) if event.was_clean => {
31+
return Poll::Ready(Ok(0));
32+
}
33+
Err(e) => return Poll::Ready(Err(io::Error::new(io::ErrorKind::Other, e))),
34+
}
35+
}};
36+
}
37+
2538
#[cfg_attr(docsrs, doc(cfg(feature = "io-util")))]
2639
impl AsyncRead for WebSocket {
2740
fn poll_read(
@@ -33,14 +46,10 @@ impl AsyncRead for WebSocket {
3346
data
3447
} else {
3548
match ready!(self.as_mut().poll_next(cx)) {
36-
Some(Ok(m)) => match m {
49+
Some(item) => match try_in_poll_io!(item) {
3750
WebSocketMessage::Text(s) => s.into_bytes(),
3851
WebSocketMessage::Bytes(data) => data,
3952
},
40-
Some(Err(WebSocketError::ConnectionClose(event))) if event.was_clean == true => {
41-
return Poll::Ready(Ok(0));
42-
}
43-
Some(Err(e)) => return Poll::Ready(Err(io::Error::new(io::ErrorKind::Other, e))),
4453
None => return Poll::Ready(Ok(0)),
4554
}
4655
};
@@ -64,26 +73,14 @@ impl AsyncWrite for WebSocket {
6473
cx: &mut Context<'_>,
6574
buf: &[u8],
6675
) -> Poll<io::Result<usize>> {
67-
macro_rules! try_in_poll {
68-
($expr:expr) => {{
69-
match $expr {
70-
Ok(o) => o,
71-
// When using `AsyncWriteExt::write_all`, `io::ErrorKind::WriteZero` will be raised.
72-
// In this case it means "attempted to write on a closed socket".
73-
Err(WebSocketError::ConnectionClose(_)) => return Poll::Ready(Ok(0)),
74-
Err(e) => return Poll::Ready(Err(io::Error::new(io::ErrorKind::Other, e))),
75-
}
76-
}};
77-
}
78-
7976
// try flushing preemptively
8077
let _ = AsyncWrite::poll_flush(self.as_mut(), cx);
8178

8279
// make sure sink is ready to send
83-
try_in_poll!(ready!(self.as_mut().poll_ready(cx)));
80+
try_in_poll_io!(ready!(self.as_mut().poll_ready(cx)));
8481

8582
// actually submit new item
86-
try_in_poll!(self.start_send(WebSocketMessage::Bytes(buf.to_vec())));
83+
try_in_poll_io!(self.start_send(WebSocketMessage::Bytes(buf.to_vec())));
8784
// ^ if no error occurred, message is accepted and queued when calling `start_send`
8885
// (i.e.: `to_vec` is called only once)
8986

0 commit comments

Comments
 (0)