From 420a23ad35661144412c313e2d00258507473b54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodolphe=20Br=C3=A9ard?= Date: Sun, 19 Mar 2023 19:29:02 +0100 Subject: [PATCH] Improve reading from stdin --- src/handshake.rs | 22 +++++++++------------- src/main.rs | 21 +++++---------------- src/stdin_reader.rs | 23 +++++++++++++++++++++++ 3 files changed, 37 insertions(+), 29 deletions(-) create mode 100644 src/stdin_reader.rs diff --git a/src/handshake.rs b/src/handshake.rs index 9086587..32aafce 100644 --- a/src/handshake.rs +++ b/src/handshake.rs @@ -1,20 +1,16 @@ -pub const CONFIG_END: &str = "config|ready"; -pub const CONFIG_TAG: &str = "config|"; +use crate::stdin_reader::StdinReader; -pub fn read_config() { - let mut buffer = String::new(); - let stdin = std::io::stdin(); +pub const CONFIG_END: &[u8] = b"config|ready\n"; +pub const CONFIG_TAG: &[u8] = b"config|"; + +pub fn read_config(reader: &mut StdinReader) { loop { - buffer.clear(); - if stdin.read_line(&mut buffer).unwrap() == 0 { - crate::eof(); - } - let entry = buffer.trim_end(); - if entry == CONFIG_END { + let line = reader.read_line(); + if line == CONFIG_END { return; } - if !entry.starts_with(CONFIG_TAG) { - eprintln!("invalid config line: {entry}"); + if !line.starts_with(CONFIG_TAG) { + eprintln!("invalid config line: {line:?}"); } } } diff --git a/src/main.rs b/src/main.rs index 255cacc..90be7d6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,16 +1,18 @@ mod entry; mod handshake; +mod stdin_reader; use entry::Entry; -use std::io::{BufRead, BufReader}; +use stdin_reader::StdinReader; const DEFAULT_BUFF_SIZE: usize = 1024; fn main() { - handshake::read_config(); + let mut reader = StdinReader::new(); + handshake::read_config(&mut reader); handshake::register_filter(); loop { - match read_line() { + match Entry::from_bytes(&reader.read_line()) { Ok(entry) => { if !entry.is_end_of_message() { println!("Debug: {entry:?}"); @@ -24,16 +26,3 @@ fn main() { } } } - -pub fn read_line() -> Result { - let mut buffer = Vec::with_capacity(DEFAULT_BUFF_SIZE); - let mut stdin = BufReader::new(std::io::stdin()); - if stdin.read_until(b'\n', &mut buffer).unwrap() == 0 { - crate::eof(); - } - Entry::from_bytes(&buffer) -} - -fn eof() { - std::process::exit(0x2a) -} diff --git a/src/stdin_reader.rs b/src/stdin_reader.rs new file mode 100644 index 0000000..e818aa9 --- /dev/null +++ b/src/stdin_reader.rs @@ -0,0 +1,23 @@ +use std::io::{BufRead, BufReader}; + +pub struct StdinReader { + reader: BufReader, + buffer: Vec, +} + +impl StdinReader { + pub fn new() -> Self { + Self { + reader: BufReader::new(std::io::stdin()), + buffer: Vec::with_capacity(crate::DEFAULT_BUFF_SIZE), + } + } + + pub fn read_line(&mut self) -> Vec { + self.buffer.clear(); + if self.reader.read_until(b'\n', &mut self.buffer).unwrap() == 0 { + std::process::exit(0) + } + self.buffer.clone() + } +}