Trim source buffer to how many bytes were read

This commit is contained in:
Yash Karandikar 2021-12-06 12:25:40 -06:00
parent b11a0f66d3
commit 8dca0b4a7f
3 changed files with 12 additions and 9 deletions

2
Cargo.lock generated
View file

@ -28,7 +28,7 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]] [[package]]
name = "circe" name = "circe"
version = "0.1.4" version = "0.1.5"
dependencies = [ dependencies = [
"native-tls", "native-tls",
"serde", "serde",

View file

@ -163,16 +163,19 @@ impl Client {
fn read_string(&mut self) -> Option<String> { fn read_string(&mut self) -> Option<String> {
let mut buffer = [0u8; 512]; let mut buffer = [0u8; 512];
match self.stream.read(&mut buffer) { let num_bytes = match self.stream.read(&mut buffer) {
Ok(_) => {} Ok(b) => b,
Err(_) => return None, 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 // Slice to the number of bytes that were actually read
// padded with a bunch of 0u8 because of the pre-allocated buffer let res = String::from_utf8_lossy(&buffer[..num_bytes]);
Some(res.trim().trim_matches(char::from(0)).trim().into())
Some(res.into())
} }
/// Read data coming from the IRC as a [`commands::Command`]. /// Read data coming from the IRC as a [`commands::Command`].

View file

@ -30,7 +30,7 @@ fn main() -> Result<(), std::io::Error> {
if message.contains("!close") { if message.contains("!close") {
client.part("#main")?; client.part("#main")?;
} }
println!("PRIVMSG received from {}: {} {}", nick, channel, message); println!("PRIVMSG received from {}: {} {:#?}", nick, channel, message);
} }
} }
} }