Improve reading from stdin

This commit is contained in:
Rodolphe Bréard 2023-03-19 19:29:02 +01:00
parent 9f8232f7f1
commit 420a23ad35
3 changed files with 37 additions and 29 deletions

View file

@ -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:?}");
}
}
}

View file

@ -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<Entry, String> {
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)
}

23
src/stdin_reader.rs Normal file
View file

@ -0,0 +1,23 @@
use std::io::{BufRead, BufReader};
pub struct StdinReader {
reader: BufReader<std::io::Stdin>,
buffer: Vec<u8>,
}
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<u8> {
self.buffer.clear();
if self.reader.read_until(b'\n', &mut self.buffer).unwrap() == 0 {
std::process::exit(0)
}
self.buffer.clone()
}
}