guessing_names 0.1.0

A fun name
Documentation

use std::error::Error;
use std::fs;
use std::env;
pub struct Config {
    pub query: String,
    pub filename: String,
    pub ignore_case: bool,
}
impl Config {
    // fn new(args: &[String]) -> Config {
    //     let query = args[1].clone();
    //     let filename = args[2].clone();
    //     Config {query, filename}
    // }
    // pub fn new(args: &[String]) -> Result<Config, &'static str> {
    //     if args.len() < 3 {
    //         return Err("No enough arguments");
    //     }
    //     let query = args[1].clone();
    //     let filename = args[2].clone();
    pub fn new(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
        args.next();
        let query = match args.next() {
            Some(args) => args,
            None => return Err("Lack of query string"),
        };
        let filename = match args.next() {
            Some(args) => args,
            None => return Err("Lack of filename string"),
        };
        let ignore_case = env::var("IGNORE_CASE").is_ok();
        Ok(Config{query, filename, ignore_case})
    }
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let content = fs::read_to_string(config.filename)?;
    // println!("With text:\n{}", content);
    let result = if config.ignore_case {
        search_case_insensitive(&config.query, &content)
    } else {
        search(&config.query, &content)
    };
        for line in result {
            println!("{}", line);
    }
    Ok(())
}

pub fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
    // let mut result = Vec::new();
    // for line in content.lines() {
    //     if line.contains(query) {
    //         result.push(line);
    //     }
    // }
    // result
    content.lines()
    .filter(|x| x.contains(query)).collect()
}

pub fn search_case_insensitive<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
    // let mut result = Vec::new();
    // let query = query.to_lowercase();
    // for line in content.lines() {
    //     if line.to_lowercase().contains(&query) {
    //         result.push(line);
    //     }
    // }
    // result
    let query = query.to_lowercase();
    content.lines()
    .filter(|x| {
        x.to_lowercase().contains(&query)
    }).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "xwp";
        let content = "\
Hello,rust!
xwp is handsome
You know!";
        assert_eq!(vec!["xwp is handsome"], search(query, content));
    }

    #[test]
    fn case_insensitive() {
        let query = "xWp";
        let content = "\
Hello,rust!
xwp is handsome
You KonW";
        assert_eq!(vec!["xwp is handsome"], search_case_insensitive(query, content));
    }
}