diff --git a/the_book/minigrep/src/lib.rs b/the_book/minigrep/src/lib.rs index b5a1b8e..1945a87 100644 --- a/the_book/minigrep/src/lib.rs +++ b/the_book/minigrep/src/lib.rs @@ -1,5 +1,5 @@ -use std::error::Error; use std::env; +use std::error::Error; use std::fs; pub fn run(config: Config) -> Result<(), Box> { @@ -22,40 +22,39 @@ pub struct Config { } impl Config { - pub fn new(args: &[String]) -> Result { - if args.len() < 3 { - return Err("Not enough arguments"); - } - let query = args[1].clone(); - let filename = args[2].clone(); + pub fn new(mut args: impl Iterator) -> Result { + args.next(); + + let query = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a query string."), + }; + let filename = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a file name."), + }; + let ignore_case = env::var("IGNORE_CASE").is_ok(); - Ok(Config { query, filename, ignore_case }) + Ok(Config { + query, + filename, + ignore_case, + }) } } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - let mut results = Vec::new(); - - for line in contents.lines() { - if line.contains(query) { - results.push(line); - } - } - - results + contents + .lines() + .filter(|line| line.contains(query)) + .collect() } pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - let query = query.to_lowercase(); - let mut results = Vec::new(); - - for line in contents.lines() { - if line.to_lowercase().contains(&query) { - results.push(line); - } - } - - results + contents + .lines() + .filter(|line| line.to_lowercase().contains(&query.to_lowercase())) + .collect() } #[cfg(test)] diff --git a/the_book/minigrep/src/main.rs b/the_book/minigrep/src/main.rs index 7d5e0a2..9c89446 100644 --- a/the_book/minigrep/src/main.rs +++ b/the_book/minigrep/src/main.rs @@ -4,9 +4,7 @@ use std::process; use minigrep::Config; fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args).unwrap_or_else(|err| { + let config = Config::new(env::args()).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); process::exit(1); });