summaryrefslogtreecommitdiff
path: root/meap/ch2/src
diff options
context:
space:
mode:
authorAdam Carpenter <53hornet@gmail.com>2019-03-27 15:48:35 -0400
committerAdam Carpenter <53hornet@gmail.com>2019-03-27 15:48:35 -0400
commite9d1b916708054a354224c6fb9cd85139da47eab (patch)
treee6992d3483da571c32fe3d59b42a958deda681b5 /meap/ch2/src
parent67cdcc2e12118becb823e20a40cc2687f2b8425a (diff)
downloadlearning-rust-e9d1b916708054a354224c6fb9cd85139da47eab.tar.xz
learning-rust-e9d1b916708054a354224c6fb9cd85139da47eab.zip
"Finished chapter 2"
Diffstat (limited to 'meap/ch2/src')
-rw-r--r--meap/ch2/src/main.rs39
1 files changed, 30 insertions, 9 deletions
diff --git a/meap/ch2/src/main.rs b/meap/ch2/src/main.rs
index 055ec1c..4d16a7a 100644
--- a/meap/ch2/src/main.rs
+++ b/meap/ch2/src/main.rs
@@ -3,6 +3,12 @@ extern crate clap;
use regex::Regex;
use clap::{App, Arg};
+use std::fs::File;
+use std::io;
+use std::io::BufReader;
+use std::io::prelude::*;
+
+
//use std::ops::{Add};
fn main() {
@@ -69,25 +75,40 @@ fn main() {
.help("the pattern to search for")
.takes_value(true)
.required(true))
+ .arg(Arg::with_name("input")
+ .help("file to search")
+ .takes_value(true))
.get_matches();
let pattern = args.value_of("pattern").unwrap();
let re = Regex::new(pattern).unwrap();
- let quote = "Every face, every shop, bedroom window, public-house, \
- and\ndark square is a picture feverishly turned--in search \
- of what?\nIt is the same with books. What do we seek through \
- millions of pages?";
- for (index, line) in quote.lines().enumerate() {
- match re.find(line) {
+ let input = args.value_of("input").unwrap_or("-");
+
+ if input == "-" {
+ let stdin = io::stdin();
+ let reader = stdin.lock();
+ process_lines(reader, re);
+ }
+ else {
+ let file = File::open(input).unwrap();
+ let reader = BufReader::new(file);
+ process_lines(reader, re);
+ }
+
+}
+
+fn process_lines<T: BufRead + Sized>(reader: T, re: Regex) {
+ for line_ in reader.lines() {
+ let line = line_.unwrap();
+
+ match re.find(&line) {
Some(_) => print!("-> "),
None => print!(" "),
};
- let line_num = index + 1;
- println!("{}: {}", line_num, line);
+ println!("{}", line);
}
-
}
//fn add<T: Add<Output = T>>(i: T, j: T) -> T {