diff options
author | Andrew Gallant <jamslam@gmail.com> | 2019-04-19 07:10:24 -0400 |
---|---|---|
committer | Andrew Gallant <jamslam@gmail.com> | 2019-04-19 07:11:44 -0400 |
commit | e7829c05d3b9234f053e7d480f7e75028831d772 (patch) | |
tree | a6323746ebba4762cc21dca77b6d1e415d4898e7 /grep-cli | |
parent | a6222939f9032b40de6065a71cf06d143dda86a3 (diff) |
cli: fix bug where last byte was stripped
In an effort to strip line terminators, we assumed their existence. But
a pattern file may not end with a line terminator, so we shouldn't
unconditionally strip them.
We fix this by moving to bstr's line handling, which does this for us
automatically.
Diffstat (limited to 'grep-cli')
-rw-r--r-- | grep-cli/src/pattern.rs | 28 |
1 files changed, 12 insertions, 16 deletions
diff --git a/grep-cli/src/pattern.rs b/grep-cli/src/pattern.rs index dbdb1d8f..2855857e 100644 --- a/grep-cli/src/pattern.rs +++ b/grep-cli/src/pattern.rs @@ -2,10 +2,12 @@ use std::error; use std::ffi::OsStr; use std::fmt; use std::fs::File; -use std::io::{self, BufRead}; +use std::io; use std::path::Path; use std::str; +use bstr::io::BufReadExt; + use escape::{escape, escape_os}; /// An error that occurs when a pattern could not be converted to valid UTF-8. @@ -156,28 +158,22 @@ pub fn patterns_from_stdin() -> io::Result<Vec<String>> { /// ``` pub fn patterns_from_reader<R: io::Read>(rdr: R) -> io::Result<Vec<String>> { let mut patterns = vec![]; - let mut bufrdr = io::BufReader::new(rdr); - let mut line = vec![]; let mut line_number = 0; - while { - line.clear(); + io::BufReader::new(rdr).for_byte_line(|line| { line_number += 1; - bufrdr.read_until(b'\n', &mut line)? > 0 - } { - line.pop().unwrap(); // remove trailing '\n' - if line.last() == Some(&b'\r') { - line.pop().unwrap(); - } - match pattern_from_bytes(&line) { - Ok(pattern) => patterns.push(pattern.to_string()), + match pattern_from_bytes(line.as_bytes()) { + Ok(pattern) => { + patterns.push(pattern.to_string()); + Ok(true) + } Err(err) => { - return Err(io::Error::new( + Err(io::Error::new( io::ErrorKind::Other, format!("{}: {}", line_number, err), - )); + )) } } - } + })?; Ok(patterns) } |