1use std::pin::Pin;
2use std::task::{Context, Poll};
3
4use rocket::data::IoStream;
5use rocket::futures::{ready, StreamExt, SinkExt, Sink};
6use rocket::futures::stream::{Stream, FusedStream};
7
8use crate::frame::{Message, CloseFrame};
9use crate::result::{Result, Error};
10
11pub struct DuplexStream(tokio_tungstenite::WebSocketStream<IoStream>, bool);
37
38impl DuplexStream {
39 pub(crate) async fn new(stream: IoStream, config: crate::Config, await_close: bool) -> Self {
42 use tokio_tungstenite::WebSocketStream;
43 use crate::tungstenite::protocol::Role;
44
45 let inner = WebSocketStream::from_raw_socket(stream, Role::Server, Some(config));
46 DuplexStream(inner.await, await_close)
47 }
48
49 pub async fn close(&mut self, msg: Option<CloseFrame>) -> Result<()> {
51 self.0.close(msg).await
52 }
53}
54
55impl Stream for DuplexStream {
56 type Item = Result<Message>;
57
58 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
59 self.get_mut().0.poll_next_unpin(cx)
60 }
61
62 fn size_hint(&self) -> (usize, Option<usize>) {
63 self.0.size_hint()
64 }
65}
66
67impl FusedStream for DuplexStream {
68 fn is_terminated(&self) -> bool {
69 self.0.is_terminated()
70 }
71}
72
73impl Sink<Message> for DuplexStream {
74 type Error = Error;
75
76 fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
77 self.get_mut().0.poll_ready_unpin(cx)
78 }
79
80 fn start_send(self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> {
81 self.get_mut().0.start_send_unpin(item)
82 }
83
84 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
85 self.get_mut().0.poll_flush_unpin(cx)
86 }
87
88 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
89 let this = self.get_mut();
90 ready!(this.0.poll_close_unpin(cx))?;
91 while this.1 {
92 match ready!(this.0.poll_next_unpin(cx)) {
93 Some(Ok(message)) if message.is_close() => break,
94 Some(Ok(_)) => continue,
95 Some(Err(e)) => return Poll::Ready(Err(e)),
96 None => break,
97 }
98 }
99
100 Poll::Ready(Ok(()))
101 }
102}