Skip to content

Commit

Permalink
added searching case insensitive using IGNORE_CASE cmd line argumenta…
Browse files Browse the repository at this point in the history
…nd outputting successful fetch to output.txt
  • Loading branch information
dhanushrajgp committed Jul 6, 2024
1 parent c3f8dd3 commit 1bc7e4d
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 8 deletions.
Binary file added output.txt
Binary file not shown.
53 changes: 48 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,39 @@
use std::{error::Error, fs};
use std::{env, error::Error, fs};

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let _content = fs::read_to_string(config.file_path)?;
let content = fs::read_to_string(config.file_path)?;

let results = if config.ignore_case {
search_case_insensitive(&config.query, &content)
} else {
search(&config.query, &content)
};
for line in results {
println!("{line}");
}
Ok(())
}

pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}

impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}

let ignore_case = env::var("IGNORE_CASE").is_ok();
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
Ok(Config {
query,
file_path,
ignore_case,
})
}
}

Expand All @@ -32,18 +48,45 @@ pub fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
results
}

pub fn search_case_insensitive<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();

for line in content.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 content = "\
Rust:
safe,fast,productive.
pick three.";
pick three
Duct Tape.";

assert_eq!(vec!["safe,fast,productive."], search(query, content))
}

#[test]
fn case_insensitive() {
let query = "rUst";
let content = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, content)
);
}
}
5 changes: 2 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@ use std::env;
use std::process;

fn main() {
println!("Hello, world!");
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);
});

if let Err(e) = minigrep::run(config) {
println!("Application error: {e}");
eprintln!("Application error: {e}");
process::exit(1)
}
}

0 comments on commit 1bc7e4d

Please sign in to comment.