monoio_native_tls/
client.rs

1use std::fmt;
2
3use monoio::io::{AsyncReadRent, AsyncWriteRent};
4
5use crate::{
6    utils::{handshake, IOWrapper},
7    TlsError, TlsStream,
8};
9
10/// A wrapper around a `native_tls::TlsConnector`, providing an async `connect`
11/// method.
12#[derive(Clone)]
13pub struct TlsConnector {
14    inner: native_tls::TlsConnector,
15    read_buffer: Option<usize>,
16    write_buffer: Option<usize>,
17}
18
19impl TlsConnector {
20    /// Connects the provided stream with this connector, assuming the provided
21    /// domain.
22    ///
23    /// This function will internally call `TlsConnector::connect` to connect
24    /// the stream and returns a future representing the resolution of the
25    /// connection operation. The returned future will resolve to either
26    /// `TlsStream<S>` or `Error` depending if it's successful or not.
27    ///
28    /// This is typically used for clients who have already established, for
29    /// example, a TCP connection to a remote server. That stream is then
30    /// provided here to perform the client half of a connection to a
31    /// TLS-powered server.
32    pub async fn connect<S>(&self, domain: &str, stream: S) -> Result<TlsStream<S>, TlsError>
33    where
34        S: AsyncReadRent + AsyncWriteRent,
35    {
36        let io = IOWrapper::new_with_buffer_size(stream, self.read_buffer, self.write_buffer);
37        handshake(move |s_wrap| self.inner.connect(domain, s_wrap), io).await
38    }
39
40    pub fn read_buffer(mut self, size: Option<usize>) -> Self {
41        self.read_buffer = size;
42        self
43    }
44
45    pub fn write_buffer(mut self, size: Option<usize>) -> Self {
46        self.write_buffer = size;
47        self
48    }
49}
50
51impl fmt::Debug for TlsConnector {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        f.debug_struct("TlsConnector").finish()
54    }
55}
56
57impl From<native_tls::TlsConnector> for TlsConnector {
58    fn from(inner: native_tls::TlsConnector) -> TlsConnector {
59        TlsConnector {
60            inner,
61            read_buffer: None,
62            write_buffer: None,
63        }
64    }
65}