From 956dbf375a4f553032f382c0c846b26815881265 Mon Sep 17 00:00:00 2001 From: "Christoph J. Scherr" Date: Fri, 19 Jan 2024 14:21:19 +0100 Subject: [PATCH] progress with the reads --- src/server/mod.rs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/server/mod.rs b/src/server/mod.rs index 5508799..54b9201 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -44,8 +44,9 @@ impl Server { } async fn handle_stream(&self, stream: (TcpStream, SocketAddr)) -> Result<()> { + const BUF_SIZE: usize = 1024; info!("start handling stream {:?}", stream.1); - let mut buf = Vec::new(); + let mut buf = [0u8; BUF_SIZE]; let mut reader = BufReader::new(stream.0); let mut len; loop { @@ -61,7 +62,7 @@ impl Server { humanbytes(len), self.decode(&buf)? ); - buf.clear(); + buf = [0; BUF_SIZE]; } } info!("stop handling stream {:?}", stream.1); @@ -69,14 +70,14 @@ impl Server { } #[inline] - fn decode(&self, buf: &Vec) -> Result { - Ok(String::from_utf8(buf.clone())?) + fn decode(&self, buf: &[u8]) -> Result { + Ok(std::str::from_utf8(buf)?.to_string()) } - async fn read(&self, reader: &mut BufReader, buf: &mut Vec) -> Result { + async fn read(&self, reader: &mut BufReader, buf: &mut [u8]) -> Result { let mut len: usize; let mut failsafe: u8 = 0; - while failsafe < u8::MAX { + while failsafe < 5 { trace!("loop"); len = match timeout(self.cfg.timeout, reader.read(buf)).await { Ok(inner) => { @@ -98,8 +99,15 @@ impl Server { Err(anyhow!("read too often, so the failsafe activated")) } - fn should_end(&self, buf: &Vec) -> bool { - debug!("eval should end: {:?}", buf); - buf.contains(&0x00) + fn should_end(&self, buf: &[u8]) -> bool { + let mut lb: u8 = buf[0]; + let mut iter = buf.iter().skip(1).peekable(); + while let Some(b) = iter.next() { + if lb != 0 && *b == 0 && **iter.peek().unwrap() == 0 { + return true + } + lb = *b; + } + return false } }