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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright (c) 2019-2022 Naja Melan
// Copyright (c) 2023-2024 Yuki Kishimoto
// Distributed under the MIT software license

use std::io;
use std::io::ErrorKind;
use std::pin::Pin;
use std::task::{Context, Poll};

use futures::prelude::{Sink, Stream};

use crate::{WsErr, WsStream};

/// A wrapper around WsStream that converts errors into io::Error so that it can be
/// used for io (like `AsyncRead`/`AsyncWrite`).
///
/// You shouldn't need to use this manually. It is passed to [`IoStream`] when calling
/// [`WsStream::into_io`].
//
#[derive(Debug)]
//
pub struct WsStreamIo {
    inner: WsStream,
}

impl WsStreamIo {
    /// Create a new WsStreamIo.
    //
    pub fn new(inner: WsStream) -> Self {
        Self { inner }
    }
}

impl Stream for WsStreamIo {
    type Item = Result<Vec<u8>, io::Error>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.inner).poll_next(cx).map(|opt| {
            opt.map(|msg| {
                msg.map(|m| m.into())
                    .map_err(|e| io::Error::new(ErrorKind::Other, e))
            })
        })
    }
}

impl Sink<Vec<u8>> for WsStreamIo {
    type Error = io::Error;

    fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.inner)
            .poll_ready(cx)
            .map(convert_res_tuple)
    }

    fn start_send(mut self: Pin<&mut Self>, item: Vec<u8>) -> Result<(), Self::Error> {
        Pin::new(&mut self.inner)
            .start_send(item.into())
            .map_err(convert_err)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.inner)
            .poll_flush(cx)
            .map(convert_res_tuple)
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.inner)
            .poll_close(cx)
            .map(convert_res_tuple)
    }
}

fn convert_res_tuple(res: Result<(), WsErr>) -> Result<(), io::Error> {
    res.map_err(convert_err)
}

fn convert_err(err: WsErr) -> io::Error {
    match err {
        WsErr::ConnectionNotOpen => io::Error::from(io::ErrorKind::NotConnected),
        // This shouldn't happen, so panic for early detection.
        _ => io::Error::from(io::ErrorKind::Other),
    }
}