Last active
August 1, 2020 03:34
-
-
Save bitristan/091f67200d6840c19c7003cfdb51f4b3 to your computer and use it in GitHub Desktop.
minigrep demo from rust book.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::process; | |
use std::fs; | |
use std::error::Error; | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
let config = Config::new(&args).unwrap_or_else(|err|{ | |
println!("Problem parsing arguements: {}", err); | |
process::exit(1); | |
}); | |
println!("Searching for {}", config.query); | |
println!("in file {}", config.filename); | |
if let Err(e) = run(config) { | |
println!("Application error: {}", e); | |
process::exit(1); | |
} | |
} | |
struct Config { | |
query: String, | |
filename: String, | |
case_sensitive: bool, | |
} | |
impl Config { | |
fn new(args: &[String]) -> Result<Config, &'static str> { | |
if args.len() < 3 { | |
return Err("not enough arguments"); | |
} | |
let query = args[1].clone(); | |
let filename = args[2].clone(); | |
let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); | |
Ok(Config { query, filename, case_sensitive }) | |
} | |
} | |
fn run(config: Config) -> Result<(), Box<dyn Error>> { | |
let content = fs::read_to_string(config.filename)?; | |
let results = if config.case_sensitive { | |
search(&config.query, &content) | |
} else { | |
search_case_insensitive(&config.query, &content) | |
}; | |
for line in results { | |
println!("{}", line); | |
} | |
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_case_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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment