From b71e253b697bae079a0cf2526209334f4b81f9a5 Mon Sep 17 00:00:00 2001 From: Adam Carpenter <53hornet@gmail.com> Date: Fri, 1 Mar 2019 14:01:17 -0500 Subject: Added functional and implemented iterators in minigrep. --- minigrep/Cargo.toml | 1 + minigrep/src/lib.rs | 54 ++++++++++++++++++---------------------------------- minigrep/src/main.rs | 3 +-- 3 files changed, 20 insertions(+), 38 deletions(-) (limited to 'minigrep') diff --git a/minigrep/Cargo.toml b/minigrep/Cargo.toml index 6a8174c..09021c1 100644 --- a/minigrep/Cargo.toml +++ b/minigrep/Cargo.toml @@ -5,3 +5,4 @@ authors = ["Adam Carpenter <53hornet@gmail.com>"] edition = "2018" [dependencies] + diff --git a/minigrep/src/lib.rs b/minigrep/src/lib.rs index bf7118f..bb8b4d7 100644 --- a/minigrep/src/lib.rs +++ b/minigrep/src/lib.rs @@ -10,26 +10,20 @@ pub struct Config { impl Config { - pub fn new(args: &[String]) -> Result { + pub fn new(mut args: std::env::Args) -> Result { + args.next(); - if args.len() < 3 { - return Err("Not enough arguments."); - } + let query = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a query string"), + }; - let query = args[1].clone(); - let filename = args[2].clone(); - let mut case_sensitive = env::var("CASE_INSENSITIVE").is_err(); - - // override environment variable if cli arg is present - if args.len() > 3 { - if args[3] == "-s" { - case_sensitive = true; - } - else if args[3] == "-i" { - case_sensitive = false; - } - } + let filename = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a filename"), + }; + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); Ok(Config { query, filename, case_sensitive }) } @@ -54,28 +48,16 @@ pub fn run(config: Config) -> Result<(), Box> { } 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() } 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/minigrep/src/main.rs b/minigrep/src/main.rs index 3cec101..c752da1 100644 --- a/minigrep/src/main.rs +++ b/minigrep/src/main.rs @@ -5,8 +5,7 @@ use minigrep; 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); }); -- cgit v1.2.3