From 8dca0b4a7fa3babbd43ac610e25ba2affda60219 Mon Sep 17 00:00:00 2001 From: Yash Karandikar Date: Mon, 6 Dec 2021 12:25:40 -0600 Subject: [PATCH] Trim source buffer to how many bytes were read --- Cargo.lock | 2 +- src/lib.rs | 17 ++++++++++------- src/main.rs | 2 +- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 269b208..9f88b9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -28,7 +28,7 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "circe" -version = "0.1.4" +version = "0.1.5" dependencies = [ "native-tls", "serde", diff --git a/src/lib.rs b/src/lib.rs index 8a1be06..3662157 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -163,16 +163,19 @@ impl Client { fn read_string(&mut self) -> Option { let mut buffer = [0u8; 512]; - match self.stream.read(&mut buffer) { - Ok(_) => {} - Err(_) => return None, + let num_bytes = match self.stream.read(&mut buffer) { + Ok(b) => b, + Err(_) => 0, }; - let res = String::from_utf8_lossy(&buffer); + if num_bytes == 0 { + return None; + } - // The trimming is required because if the message is less than 512 bytes it will be - // padded with a bunch of 0u8 because of the pre-allocated buffer - Some(res.trim().trim_matches(char::from(0)).trim().into()) + // Slice to the number of bytes that were actually read + let res = String::from_utf8_lossy(&buffer[..num_bytes]); + + Some(res.into()) } /// Read data coming from the IRC as a [`commands::Command`]. diff --git a/src/main.rs b/src/main.rs index 2a532ad..d399413 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,7 +30,7 @@ fn main() -> Result<(), std::io::Error> { if message.contains("!close") { client.part("#main")?; } - println!("PRIVMSG received from {}: {} {}", nick, channel, message); + println!("PRIVMSG received from {}: {} {:#?}", nick, channel, message); } } }