minigrep_2025 0.1.0

minigrep
Documentation

use std::error::Error;

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

    let result:Vec<&str> = if !config.ignore_case{
        search(&config.query, &contents)
    }else {
        search_case(&config.query, &contents)
    };
    for line in result{
        println!("{}", line);
    }
    Ok(())
}

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

impl Config {
    pub fn build(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
        args.next();
        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a query string"),
        };
        let file_path = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a file name"),
        };

        let ignore_case = std::env::var("IGNORE_CASE").is_ok();
        Ok(Config {
            query,
            file_path,
            ignore_case,
        })
    }
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents.lines().filter(|line| line.contains(query)).collect()
}
pub fn search_case<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let query = query.to_lowercase();
    contents.lines().filter(|line| line.to_lowercase().contains(&query)).collect()
}
#[cfg(test)]
mod tests{
    use super::*;
    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";
        assert_eq!(vec!["safe, fast, productive."],search(query, contents));
    }
    #[test]
    fn case_sensitive() {
        let query = "rUst";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
rust";
        assert_eq!(vec!["Rust:","rust"],search_case(query, contents));
    }
}