diff options
author | Adam Carpenter <53hornet@gmail.com> | 2019-03-01 14:01:17 -0500 |
---|---|---|
committer | Adam Carpenter <53hornet@gmail.com> | 2019-03-01 14:01:17 -0500 |
commit | b71e253b697bae079a0cf2526209334f4b81f9a5 (patch) | |
tree | 0251289af1860305903760f719821593a672ed39 /minigrep/src/lib.rs | |
parent | db0289b1813b73a93c22f12379ba501dbadc7552 (diff) | |
download | learning-rust-b71e253b697bae079a0cf2526209334f4b81f9a5.tar.xz learning-rust-b71e253b697bae079a0cf2526209334f4b81f9a5.zip |
Added functional and implemented iterators in minigrep.
Diffstat (limited to 'minigrep/src/lib.rs')
-rw-r--r-- | minigrep/src/lib.rs | 54 |
1 files changed, 18 insertions, 36 deletions
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<Config, &'static str> { + pub fn new(mut args: std::env::Args) -> Result<Config, &'static str> { + 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<dyn Error>> { } 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)] |