1use std::io;
6use std::io::ErrorKind;
7use std::pin::Pin;
8use std::task::{Context, Poll};
9
10use futures::prelude::{Sink, Stream};
11
12use crate::{WsErr, WsStream};
13
14#[derive(Debug)]
21pub struct WsStreamIo {
23 inner: WsStream,
24}
25
26impl WsStreamIo {
27 pub fn new(inner: WsStream) -> Self {
30 Self { inner }
31 }
32}
33
34impl Stream for WsStreamIo {
35 type Item = Result<Vec<u8>, io::Error>;
36
37 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
38 Pin::new(&mut self.inner).poll_next(cx).map(|opt| {
39 opt.map(|msg| {
40 msg.map(|m| m.into())
41 .map_err(|e| io::Error::new(ErrorKind::Other, e))
42 })
43 })
44 }
45}
46
47impl Sink<Vec<u8>> for WsStreamIo {
48 type Error = io::Error;
49
50 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
51 Pin::new(&mut self.inner)
52 .poll_ready(cx)
53 .map(convert_res_tuple)
54 }
55
56 fn start_send(mut self: Pin<&mut Self>, item: Vec<u8>) -> Result<(), Self::Error> {
57 Pin::new(&mut self.inner)
58 .start_send(item.into())
59 .map_err(convert_err)
60 }
61
62 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
63 Pin::new(&mut self.inner)
64 .poll_flush(cx)
65 .map(convert_res_tuple)
66 }
67
68 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
69 Pin::new(&mut self.inner)
70 .poll_close(cx)
71 .map(convert_res_tuple)
72 }
73}
74
75fn convert_res_tuple(res: Result<(), WsErr>) -> Result<(), io::Error> {
76 res.map_err(convert_err)
77}
78
79fn convert_err(err: WsErr) -> io::Error {
80 match err {
81 WsErr::ConnectionNotOpen => io::Error::from(io::ErrorKind::NotConnected),
82 _ => io::Error::from(io::ErrorKind::Other),
84 }
85}