From 2df4a7a7ce08b85a75ebba05f48376b3521c5a6b Mon Sep 17 00:00:00 2001 From: famfo Date: Sun, 2 Jan 2022 09:57:28 +0100 Subject: [PATCH] Use BufReader to read new lines --- src/lib.rs | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 6b8ebe9..8c0769f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,8 +22,9 @@ #![allow(clippy::too_many_lines)] #![cfg_attr(docsrs, feature(doc_cfg))] +use tokio::io::BufReader; use tokio::io::Error; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::io::{AsyncWriteExt, AsyncBufReadExt}; use tokio::net::TcpStream; #[cfg(feature = "tls")] @@ -43,9 +44,9 @@ pub mod commands; pub struct Client { config: Config, #[cfg(not(feature = "tls"))] - stream: TcpStream, + buf_reader: BufReader, #[cfg(feature = "tls")] - stream: tokio_native_tls::TlsStream, + buf_reader: BufReader>, } /// Config for the IRC client @@ -91,6 +92,7 @@ impl Client { .unwrap(); tracing::debug!("New TcpStream created"); + #[cfg(feature = "tls")] { let connector = TlsConnector::builder().build().unwrap(); @@ -101,14 +103,19 @@ impl Client { .await .unwrap(); + let buf_reader = BufReader::new(sslstream); + return Ok(Self { config, - stream: sslstream, + buf_reader, }); }; #[cfg(not(feature = "tls"))] - return Ok(Self { config, stream }); + { + let buf_reader = BufReader::new(stream); + return Ok(Self { config, buf_reader }); + }; } /// Identify user and joins the in the [`Config`] specified channels. @@ -179,9 +186,9 @@ impl Client { } async fn read_string(&mut self) -> Result, tokio::io::Error> { - let mut buffer = [0u8; 512]; + let mut buffer = String::new(); - let num_bytes = match self.stream.read(&mut buffer).await { + let num_bytes = match self.buf_reader.read_line(&mut buffer).await { Ok(b) => b, Err(e) => { tracing::error!("{}", e); @@ -194,9 +201,9 @@ impl Client { } // Slice to the number of bytes that were actually read - let res = String::from_utf8_lossy(&buffer[..num_bytes]); + //let res = String::from_utf8_lossy(&buffer[..num_bytes]); - Ok(Some(res.into())) + Ok(Some(buffer.into())) } /// Read data coming from the IRC as a [`commands::Command`]. @@ -234,7 +241,7 @@ impl Client { async fn write(&mut self, data: String) -> Result<(), Error> { tracing::debug!("{:?}", data); - self.stream.write_all(data.as_bytes()).await?; + self.buf_reader.write_all(data.as_bytes()).await?; Ok(()) } @@ -587,7 +594,7 @@ impl Client { .await?; } tracing::info!("async-circe shutting down"); - self.stream.shutdown().await?; + self.buf_reader.shutdown().await?; Ok(()) }