Skip to content

Instantly share code, notes, and snippets.

@danieldk
Created May 26, 2016 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieldk/3bd3b84c1a7c8bc8c902314a488cd210 to your computer and use it in GitHub Desktop.
Save danieldk/3bd3b84c1a7c8bc8c902314a488cd210 to your computer and use it in GitHub Desktop.
use std::io;
use std::fs;
use std::env;
use std::fmt;
use std::process;
use std::collections::{HashMap, HashSet};
use std::io::BufRead;
pub fn or_exit<T, E: fmt::Display>(r: Result<T, E>) -> T {
r.unwrap_or_else(|e: E| -> T {
println!("Error: {}", e);
process::exit(1)
})
}
fn main() {
let mut idx = HashMap::new();
for fname in env::args().skip(1) {
let reader = or_exit(fs::File::open(&fname).map(io::BufReader::new));
for line in reader.lines() {
let line = or_exit(line);
for token in line.split_whitespace() {
idx.entry(token.to_owned())
.or_insert(HashSet::new())
.insert(fname.to_owned());
}
}
}
println!("Please enter a search term and press enter:");
print!("> ");
let stdin = io::stdin();
for query in stdin.lock().lines() {
match idx.get(&query.unwrap()) {
Some(files) => println!("appears in {:?}", files),
None => println!("does not appear in any files"),
};
print!("> ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment