From e16f7ec2ad736c438fabcfbbfa03e270e7a96036 Mon Sep 17 00:00:00 2001 From: Breno Viana Date: Thu, 16 Apr 2020 20:01:18 -0300 Subject: [PATCH] improves the initialization function ('new') of the search config structure --- src/lib.rs | 28 ++++++++++++++++++---------- src/main.rs | 4 +--- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index cc047c0..846a7e3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,18 +18,26 @@ pub struct Config { impl Config { /// Gets the arguments, validates them and returns the search configuration. - pub fn new(args: &[String]) -> Result { - // Check if the arguments are valid - match args.len() { - 3 => { /* Right number of arguments. */ }, - 0 => return Err("how did you do it?"), - 1 => return Err("you did not enter any arguments."), - 2 => return Err("you did not enter the filename."), - _ => println!(" WARNING: You have entered more arguments than needed."), + pub fn new(mut args: std::env::Args) -> Result { + // Skip program call + args.next(); + // Get query string from arguments + let query = match args.next() { + Some(arg) => arg, + None => return Err("you did not enter a string."), + }; + // Get query filename from arguments + let filename = match args.next() { + Some(arg) => arg, + None => return Err("you did not enter the filename"), + }; + // Check if the case insensitive variable is active + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + // Check if there are still arguments + if let Some(_) = args.next() { + println!(" WARNING: You have entered more arguments than needed."); } // Return the search configuration - let (query, filename, case_sensitive) = - (args[1].clone(), args[2].clone(), env::var("CASE_INSENSITIVE").is_err()); Ok(Config{ query, filename, case_sensitive }) } } diff --git a/src/main.rs b/src/main.rs index 3d4313e..dbafb12 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,10 +10,8 @@ use std::process; use minigrep::Config; fn main() { - // Get arguments - let args: Vec = env::args().collect(); // Get the search configuration - 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); });