rusty_express/core/
stream.rs

1#![allow(dead_code)]
2
3use std::io::{self, prelude::*, Error, ErrorKind};
4use std::net::{Shutdown, SocketAddr, TcpStream};
5use std::time::Duration;
6
7use crate::native_tls::TlsStream;
8
9pub(crate) enum Stream {
10    Tcp(TcpStream),
11    Tls(Box<TlsStream<TcpStream>>),
12}
13
14impl Stream {
15    pub(crate) fn shutdown(&mut self, how: Shutdown) -> io::Result<()> {
16        match self {
17            Stream::Tcp(tcp) => tcp.shutdown(how),
18            Stream::Tls(ref mut tls) => tls.shutdown(),
19        }
20    }
21
22    pub(crate) fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
23        match self {
24            Stream::Tcp(tcp) => tcp.set_read_timeout(dur),
25            Stream::Tls(tls) => tls.get_ref().set_read_timeout(dur),
26        }
27    }
28
29    pub(crate) fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
30        match self {
31            Stream::Tcp(tcp) => tcp.set_write_timeout(dur),
32            Stream::Tls(tls) => tls.get_ref().set_write_timeout(dur),
33        }
34    }
35
36    pub(crate) fn take_error(&self) -> io::Result<Option<io::Error>> {
37        match self {
38            Stream::Tcp(tcp) => tcp.take_error(),
39            Stream::Tls(tls) => tls.get_ref().take_error(),
40        }
41    }
42
43    pub(crate) fn peer_addr(&self) -> io::Result<SocketAddr> {
44        match self {
45            Stream::Tcp(tcp) => tcp.peer_addr(),
46            Stream::Tls(tls) => tls.get_ref().peer_addr(),
47        }
48    }
49
50    // Side effect: TLS stream will be downgraded to TCP stream since the handshake has been done
51    pub(crate) fn try_clone(&self) -> io::Result<Stream> {
52        match self {
53            Stream::Tcp(tcp) => tcp.try_clone().map(Stream::Tcp),
54            _ => Err(Error::new(
55                ErrorKind::InvalidInput,
56                "TLS connection shouldn't be kept long-live",
57            )),
58        }
59    }
60
61    pub(crate) fn is_tls(&self) -> bool {
62        match self {
63            Stream::Tls(_) => true,
64            _ => false,
65        }
66    }
67}
68
69impl Read for Stream {
70    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
71        match self {
72            Stream::Tcp(tcp) => tcp.read(buf),
73            Stream::Tls(tls) => tls.read(buf),
74        }
75    }
76}
77
78impl Write for Stream {
79    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
80        match self {
81            Stream::Tcp(tcp) => tcp.write(buf),
82            Stream::Tls(tls) => tls.write(buf),
83        }
84    }
85
86    fn flush(&mut self) -> io::Result<()> {
87        match self {
88            Stream::Tcp(tcp) => tcp.flush(),
89            Stream::Tls(tls) => tls.flush(),
90        }
91    }
92}