forked from compio-rs/compio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.rs
More file actions
93 lines (83 loc) · 2.49 KB
/
stream.rs
File metadata and controls
93 lines (83 loc) · 2.49 KB
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
86
87
88
89
90
91
92
93
//! Provides [`MaybeTlsStream`].
#[cfg(feature = "rustls")]
use std::io::Result as IoResult;
#[cfg(feature = "rustls")]
use compio_buf::{BufResult, IoBuf, IoBufMut};
#[cfg(feature = "rustls")]
use compio_io::{AsyncRead, AsyncWrite};
#[cfg(feature = "rustls")]
use compio_tls::TlsStream;
/// Stream that can be either plain TCP or TLS-encrypted
#[cfg(feature = "rustls")]
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum MaybeTlsStream<S> {
/// Plain, unencrypted stream
Plain(S),
/// TLS-encrypted stream
#[cfg(feature = "rustls")]
Tls(TlsStream<S>),
}
#[cfg(feature = "rustls")]
impl<S> MaybeTlsStream<S> {
/// Create an unencrypted stream.
pub fn plain(stream: S) -> Self {
MaybeTlsStream::Plain(stream)
}
/// Create a TLS-encrypted stream.
#[cfg(feature = "rustls")]
pub fn tls(stream: TlsStream<S>) -> Self {
MaybeTlsStream::Tls(stream)
}
/// Whether the stream is TLS-encrypted.
pub fn is_tls(&self) -> bool {
#[cfg(feature = "rustls")]
{
matches!(self, MaybeTlsStream::Tls(_))
}
#[cfg(not(feature = "rustls"))]
{
false
}
}
}
#[cfg(feature = "rustls")]
impl<S> AsyncRead for MaybeTlsStream<S>
where
S: AsyncRead + AsyncWrite + Unpin + 'static,
{
async fn read<B: IoBufMut>(&mut self, buf: B) -> BufResult<usize, B> {
match self {
MaybeTlsStream::Plain(stream) => stream.read(buf).await,
#[cfg(feature = "rustls")]
MaybeTlsStream::Tls(stream) => stream.read(buf).await,
}
}
}
#[cfg(feature = "rustls")]
impl<S> AsyncWrite for MaybeTlsStream<S>
where
S: AsyncRead + AsyncWrite + Unpin + 'static,
{
async fn write<B: IoBuf>(&mut self, buf: B) -> BufResult<usize, B> {
match self {
MaybeTlsStream::Plain(stream) => stream.write(buf).await,
#[cfg(feature = "rustls")]
MaybeTlsStream::Tls(stream) => stream.write(buf).await,
}
}
async fn flush(&mut self) -> IoResult<()> {
match self {
MaybeTlsStream::Plain(stream) => stream.flush().await,
#[cfg(feature = "rustls")]
MaybeTlsStream::Tls(stream) => stream.flush().await,
}
}
async fn shutdown(&mut self) -> IoResult<()> {
match self {
MaybeTlsStream::Plain(stream) => stream.shutdown().await,
#[cfg(feature = "rustls")]
MaybeTlsStream::Tls(stream) => stream.shutdown().await,
}
}
}