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 {
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)?;
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> {
content.lines()
.filter(|x| x.contains(query)).collect()
}
pub fn search_case_insensitive<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
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));
}
}