minigrep_wise 0.1.0

This is an implementation of the minigrep project from the rust book project
Documentation
//! # Minigrep
//!
//! A library containing all the functions needed for minigrep handling.

use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;

/// Config struct to define how arguments are behind structed
/// # Example
/// ```
/// use minigrep_wise::Config;
/// let data = Config {
///             query: "hello".to_string(),
///             filename:"poem.txt".to_string(),
///             case_sensitive: true
/// };
/// assert_eq!(data.query, "hello");
/// assert_eq!(data.filename, "poem.txt");
/// assert_eq!(data.case_sensitive, true);
/// ```
pub struct Config {
    pub query: String,
    pub filename: String,
    pub case_sensitive: bool,
}

/// The implementation functionality of Config struct
impl Config {
    /// Config new is used to create a Config object from a series of parameters gotten from the
    /// command line
    pub fn new(mut args: env::Args) -> Result<Config, &'static str> {
        args.next();

        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a query string"),
        };

        let filename = match args.next() {
            Some(arg) => arg,
            None => return Err("Did't get a file name"),
        };

        let case_sensitive = env::var("CASE_INSENSITIVE").is_err();

        Ok(Config {
            query,
            filename,
            case_sensitive,
        })
    }
}

/// Program entry point for handling Config and processing output
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let mut f = File::open(config.filename)?;

    let mut contents = String::new();

    f.read_to_string(&mut contents)?;

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

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

    Ok(())
}

/// Handles the search logic for case sensitive file content search
/// # Example
/// ```
/// use minigrep_wise::search;
/// let query = "duct";
/// let contents = "Rust:\nsafe, fast, productive.\nPick three.";
/// assert_eq!(vec!["safe, fast, productive."], search(query, contents));
/// ```
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents
        .lines()
        .filter(|line| line.contains(query))
        .collect()
}

/// Handles the search logic for case insenstive file content search
/// # Example
/// ```
/// use minigrep_wise::search_case_insensitive;
/// let query = "duct";
/// let contents = "Rust:\nsafe, fast, productive.\nPick three.";
/// assert_eq!(vec!["safe, fast, productive."], search_case_insensitive(query, contents));
/// ```
pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents
        .lines()
        .filter(|line| line.to_lowercase().contains(&query.to_lowercase()))
        .collect()
}

#[cfg(test)]
mod test {
    use std::vec;

    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";

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