Created
December 28, 2016 02:33
-
-
Save anonymous/bfa42d4f86e03695f3c880aaceca2088 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate regex; | |
use std::env; | |
use std::error; | |
use std::fs::File; | |
use std::io::{self, BufRead, Write}; | |
use std::process; | |
use regex::bytes::Regex; | |
type Error = Box<error::Error + Send + Sync>; | |
fn main() { | |
match run() { | |
Ok(count) => println!("{}", count), | |
Err(err) => { | |
let _ = writeln!(&mut io::stderr(), "{}", err); | |
process::exit(1); | |
} | |
} | |
} | |
fn run() -> Result<u64, Error> { | |
let (fpath, query) = match (env::args_os().nth(1), env::args().nth(2)) { | |
(None, _) => return Err(Error::from("missing file to search")), | |
(_, None) => return Err(Error::from("missing search query")), | |
(Some(fpath), Some(query)) => (fpath, query), | |
}; | |
let query_re = Regex::new(®ex::quote(&query))?; | |
let mut count = 0; | |
let mut rdr = io::BufReader::new(File::open(fpath)?); | |
let mut line = vec![]; | |
while rdr.read_until(b'\n', &mut line)? > 0 { | |
if query_re.is_match(&line) { | |
count += 1; | |
} | |
line.clear(); | |
} | |
Ok(count) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment