1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use std::{
io::{Error as IoError, Result as IoResult},
pin::Pin,
task::{Context, Poll},
};
use futures_util::{Sink, SinkExt, Stream, StreamExt};
use super::{utils::tungstenite_error_to_io_error, Message};
use crate::Upgraded;
pub struct WebSocketStream {
inner: tokio_tungstenite::WebSocketStream<Upgraded>,
}
impl WebSocketStream {
pub(crate) fn new(inner: tokio_tungstenite::WebSocketStream<Upgraded>) -> Self {
Self { inner }
}
}
impl Stream for WebSocketStream {
type Item = IoResult<Message>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.inner.poll_next_unpin(cx) {
Poll::Ready(Some(Ok(msg))) => Poll::Ready(Some(Ok(msg.into()))),
Poll::Ready(Some(Err(err))) => {
Poll::Ready(Some(Err(tungstenite_error_to_io_error(err))))
}
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
impl Sink<Message> for WebSocketStream {
type Error = IoError;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner
.poll_ready_unpin(cx)
.map_err(tungstenite_error_to_io_error)
}
fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> {
self.inner
.start_send_unpin(item.into())
.map_err(tungstenite_error_to_io_error)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner
.poll_flush_unpin(cx)
.map_err(tungstenite_error_to_io_error)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner
.poll_close_unpin(cx)
.map_err(tungstenite_error_to_io_error)
}
}