Made the irc-stream not block if it has messages in the buffer

and added some cleaning for the incoming messages.
This commit is contained in:
Daniel Mowitz 2021-05-03 01:41:01 +02:00
parent 5d134f716d
commit bf53e62f17

View file

@ -37,22 +37,24 @@ pub struct IrcStream<S: Read + Write> {
impl<S: Read + Write> IrcRead for IrcStream<S> {
fn read(&mut self) -> Result<Message> {
let mut message: Option<Message> = 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."))
}
}