From bf53e62f1713dfe83198f75992cc0e889de398ff Mon Sep 17 00:00:00 2001 From: DanielMowitz Date: Mon, 3 May 2021 01:41:01 +0200 Subject: [PATCH] Made the irc-stream not block if it has messages in the buffer and added some cleaning for the incoming messages. --- src/lib.rs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 1f63c48..bb2e1d8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -37,22 +37,24 @@ pub struct IrcStream { impl IrcRead for IrcStream { fn read(&mut self) -> Result { - let mut message: Option = None; - while message == None { - let mut temp_buf = [0; 512]; - self.stream.read(&mut temp_buf)?; - self.buffer.push_str(std::str::from_utf8(&temp_buf)?); - match self.buffer.find("\r\n") { + loop { + match self.buffer.find("\n") { Some(i) => { let mut raw_message = self.buffer.clone(); + // This returns the part after the line break to the buffer. - self.buffer = raw_message.split_off(i+2); - message = Some(Message::from(raw_message.as_str())); + self.buffer = raw_message.split_off(i+1); + + // Trim null bytes for good measure. + raw_message = String::from(raw_message.trim_matches('\u{0}')); + return Ok(Message::from(raw_message.as_str())); }, None => (), } + let mut temp_buf = [0; 512]; + self.stream.read(&mut temp_buf)?; + self.buffer.push_str(std::str::from_utf8(&temp_buf)?); } - Ok(message.expect("Got no message.")) } }