async_tungstenite/
stream.rs

1//! Convenience wrapper for streams to switch between plain TCP and TLS at runtime.
2//!
3//!  There is no dependency on actual TLS implementations. Everything like
4//! `native_tls` or `openssl` will work as long as there is a TLS stream supporting standard
5//! `AsyncRead + AsyncWrite` traits.
6use std::pin::Pin;
7use std::task::{Context, Poll};
8
9use futures_io::{AsyncRead, AsyncWrite};
10
11/// Stream, either plain TCP or TLS.
12#[derive(Debug)]
13pub enum Stream<S, T> {
14    /// Unencrypted socket stream.
15    Plain(S),
16    /// Encrypted socket stream.
17    Tls(T),
18}
19
20impl<S: AsyncRead + Unpin, T: AsyncRead + Unpin> AsyncRead for Stream<S, T> {
21    fn poll_read(
22        self: Pin<&mut Self>,
23        cx: &mut Context<'_>,
24        buf: &mut [u8],
25    ) -> Poll<std::io::Result<usize>> {
26        match self.get_mut() {
27            Stream::Plain(ref mut s) => Pin::new(s).poll_read(cx, buf),
28            Stream::Tls(ref mut s) => Pin::new(s).poll_read(cx, buf),
29        }
30    }
31}
32
33impl<S: AsyncWrite + Unpin, T: AsyncWrite + Unpin> AsyncWrite for Stream<S, T> {
34    fn poll_write(
35        self: Pin<&mut Self>,
36        cx: &mut Context<'_>,
37        buf: &[u8],
38    ) -> Poll<Result<usize, std::io::Error>> {
39        match self.get_mut() {
40            Stream::Plain(ref mut s) => Pin::new(s).poll_write(cx, buf),
41            Stream::Tls(ref mut s) => Pin::new(s).poll_write(cx, buf),
42        }
43    }
44
45    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> {
46        match self.get_mut() {
47            Stream::Plain(ref mut s) => Pin::new(s).poll_flush(cx),
48            Stream::Tls(ref mut s) => Pin::new(s).poll_flush(cx),
49        }
50    }
51
52    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> {
53        match self.get_mut() {
54            Stream::Plain(ref mut s) => Pin::new(s).poll_close(cx),
55            Stream::Tls(ref mut s) => Pin::new(s).poll_close(cx),
56        }
57    }
58}