v0.1.3: add tests, case insensitive search

This commit is contained in:
AJ ONeal 2018-09-18 22:06:28 -06:00
parent e08b9a3b8a
commit 4d72618bb9
1 changed files with 75 additions and 11 deletions

View File

@ -1,27 +1,56 @@
use std::fs::File; use std::fs;
use std::io::prelude::*; //use std::fs::File;
//use std::io::prelude::*;
use std::error::Error; use std::error::Error;
use std::env;
pub struct Config { pub struct Config {
query: String, query: String,
filename: String, filename: String,
insensitive: bool,
} }
pub fn run(conf: Config) -> Result<(), Box<Error>> { pub fn run(conf: Config) -> Result<(), Box<dyn Error>> {
println!("{:?} {:?}", conf.query, conf.filename); let contents = fs::read_to_string(conf.filename)?;
let mut f = File::open(&conf.filename)?; let results = if conf.insensitive {
search(&conf.query, &contents)
} else {
search_insensitive(&conf.query, &contents)
};
let mut contents = String::new(); for line in results {
f.read_to_string(&mut contents)?; println!("{}", line);
}
println!("Searching for '{}'", conf.query);
println!("In file '{}'", conf.filename);
println!("With text:\n{}", contents);
Ok(()) Ok(())
} }
fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
fn search_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
impl Config { impl Config {
pub fn new(args: &[String]) -> Result<Config, &'static str> { pub fn new(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 { if args.len() < 3 {
@ -31,6 +60,41 @@ impl Config {
Ok(Config { Ok(Config {
query: args[1].clone(), query: args[1].clone(),
filename: args[2].clone(), filename: args[2].clone(),
insensitive: env::var("CASE_INSENSITIVE").is_err(),
}) })
} }
} }
#[cfg(test)]
mod tests {
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_insensitive(query, contents)
);
}
}