Finished project.

This commit is contained in:
Ada Werefox 2023-03-11 23:59:46 +00:00
parent ee9858663c
commit 13eb0a182a
2 changed files with 49 additions and 6 deletions

View File

@ -1,9 +1,11 @@
use std::env;
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}
impl Config {
@ -15,14 +17,26 @@ impl Config {
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config {
query,
file_path,
ignore_case,
})
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
for line in search(&config.query, &contents) {
let results = if config.ignore_case {
search_case_insensitive(&config.query, &contents)
} else {
search(&config.query, &contents)
};
for line in results {
println!("{line}");
}
@ -41,18 +55,47 @@ pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
results
}
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
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick tthree.";
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents))
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}

View File

@ -7,7 +7,7 @@ fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::build(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {err}");
eprintln!("Problem parsing arguments: {err}");
process::exit(1);
});
@ -15,7 +15,7 @@ fn main() {
// println!("In file {}", config.file_path);
if let Err(e) = minigrep::run(config) {
println!("Application error: {e}");
eprintln!("Application error: {e}");
process::exit(1);
}
}