Skip to content
This repository has been archived by the owner on Feb 12, 2024. It is now read-only.

Commit

Permalink
improves the initialization function ('new') of the search config str…
Browse files Browse the repository at this point in the history
…ucture
  • Loading branch information
brenomfviana committed Apr 16, 2020
1 parent 77d7425 commit e16f7ec
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
28 changes: 18 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Config, &'static str> {
// 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<Config, &'static str> {
// 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 })
}
}
Expand Down
4 changes: 1 addition & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,8 @@ use std::process;
use minigrep::Config;

fn main() {
// Get arguments
let args: Vec<String> = 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);
});
Expand Down

0 comments on commit e16f7ec

Please sign in to comment.