Help putting rustls::Stream into a structure

heres what i tried

use std::{io::Write, net::TcpStream};
use std::sync::Arc;

use rustls::{ClientConnection, RootCertStore, Stream};

fn main() {
    let mut client = Client::new();
    client.stream.write_all(b"hello");
}

impl<'a> Client<'a> {
    fn new() -> Self {
        let root_store = RootCertStore {
            roots: webpki_roots::TLS_SERVER_ROOTS.into(),
        };
        let mut config = rustls::ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth();
    
        // Allow using SSLKEYLOGFILE.
        config.key_log = Arc::new(rustls::KeyLogFile::new());
    
        let server_name = "www.rust-lang.org".try_into().unwrap();
        let mut conn = rustls::ClientConnection::new(Arc::new(config), server_name).unwrap();
        let mut sock = TcpStream::connect("www.rust-lang.org:443").unwrap();
        let mut tls = rustls::Stream::new(&mut conn, &mut sock);
        Client { stream: &mut tls}
    }
}

struct Client<'a> {
    stream: &'a mut Stream<'a, ClientConnection, TcpStream>,
}
  1. &a mut Thing<'a> is never what you want
  2. You can't return a borrow of a local, and Stream<'_, _, _> contains such a borrow
    a. This signature where 'a comes out of nowhere is a clue related to that
    impl<'a> Client<'a> {
        // aka `fn new() -> Client<'a>`
        fn new() -> Self {
    
    b. You can't return all of conn, sock, and Stream<'_, _, _> either as that would be a self-referencial return type

Use StreamOwned instead.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.