From a79cd5d56616f0a8f8044b182d21ab871866abbf Mon Sep 17 00:00:00 2001 From: shy Date: Fri, 16 Apr 2021 16:40:12 +0200 Subject: [PATCH] Refactored stdin parsing. --- src/alarm.rs | 28 ++++++++++++---------------- src/main.rs | 1 - 2 files changed, 12 insertions(+), 17 deletions(-) diff --git a/src/alarm.rs b/src/alarm.rs index f592a36..84d5fa8 100644 --- a/src/alarm.rs +++ b/src/alarm.rs @@ -1,5 +1,6 @@ use std::io::Write; use std::process::{Command, Stdio, Child}; +use std::io::BufRead; use termion::{color, cursor, style}; use termion::raw::RawTerminal; use unicode_width::UnicodeWidthStr; @@ -350,24 +351,19 @@ impl AlarmRoster { pub fn from_stdin(&mut self, stdin: std::io::Stdin) -> Result<(), String> { - let mut buffer = String::new(); - loop { - buffer.clear(); - match stdin.read_line(&mut buffer) { - Ok(0) => break, // EOF. - Ok(1) => continue, // Empty (newline only). - Ok(_) if buffer.starts_with('#') => continue, - Ok(_) => (), + for line in stdin.lock().lines() { + match line { + Ok(line) + if !line.starts_with('#') + && !line.trim().is_empty() + => { + if let Err(e) = self.add(&line) { + return Err(format!("Value \"{}\": {}", line, e)); + } + }, + Ok(_) => (), // Discard comments and empty lines. Err(e) => return Err(e.to_string()), } - // Strip newline. - if buffer.ends_with('\n') { buffer.pop(); } - // Ignore lines containing only white spaces. - if buffer.contains(|c: char| !c.is_whitespace()) { - if let Err(e) = self.add(&buffer) { - return Err(format!("Value \"{}\": {}",buffer, e)); - } - } } Ok(()) } diff --git a/src/main.rs b/src/main.rs index 05e2b9b..645fca4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,6 @@ fn main() { // Read alarm times from stdin if stdin is not a tty. let stdin = std::io::stdin(); if !termion::is_tty(&stdin) { - stdin.lock(); if let Err(e) = alarm_roster.from_stdin(stdin) { eprintln!("Error while reading alarm times from stdin. ({})", e); process::exit(1);