zrbecker-minigrep 0.1.0

a mini version of the grep tool
Documentation
use std::{env, error::Error, fs};

pub enum ConfigErr {
    InvalidArgs,
}

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, ConfigErr> {
        args.next();

        let query = match args.next() {
            Some(arg) => arg,
            None => return Err(ConfigErr::InvalidArgs),
        };

        let file_path = match args.next() {
            Some(arg) => arg,
            None => return Err(ConfigErr::InvalidArgs),
        };

        let ignore_case = match env::var("MINIGREP_IGNORE_CASE") {
            Ok(val) => val == "1" || val.eq_ignore_ascii_case("true"),
            Err(_) => false,
        };

        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)?;

    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Box<[&'a str]> {
    contents
        .lines()
        .filter(|line| line.contains(query))
        .collect()
}

pub fn contains_ignore_case(haystack: &str, needle: &str) -> bool {
    let mut haystack_it = haystack.chars().peekable();

    while haystack_it.peek().is_some() {
        if haystack_it
            .clone()
            .zip(needle.chars())
            .all(|(a, b)| a.to_lowercase().eq(b.to_lowercase()))
        {
            return true;
        }

        haystack_it.next();
    }

    false
}

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Box<[&'a str]> {
    contents
        .lines()
        .filter(|line| contains_ignore_case(line, 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!(
            ["safe, fast, productive."],
            search(query, contents).as_ref()
        );
    }

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
        assert_eq!(
            ["safe, fast, productive."],
            search(query, contents).as_ref()
        );
    }

    #[test]
    fn ignore_case() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
        assert_eq!(
            ["Rust:", "Trust me."],
            search_case_insensitive(query, contents).as_ref()
        );
    }
}