From 07bff7409b54c09571d0fb17da084917d356c8c0 Mon Sep 17 00:00:00 2001
From: Andrew Gallant <jamslam@gmail.com>
Date: Wed, 30 Mar 2016 22:24:59 -0400
Subject: [PATCH] tweaks

---
 src/main.rs   | 13 +++++++++++--
 src/search.rs | 14 +++++++++-----
 2 files changed, 20 insertions(+), 7 deletions(-)

diff --git a/src/main.rs b/src/main.rs
index 59a08ce4..c1bb7ff8 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -9,6 +9,9 @@ extern crate rustc_serialize;
 
 const USAGE: &'static str = "
 Usage: rep [options] <pattern> [<file> ...]
+
+Options:
+    -c, --count   Suppress normal output and show count of matches.
 ";
 
 use std::error::Error;
@@ -32,6 +35,7 @@ pub type Result<T> = result::Result<T, Box<Error + Send + Sync>>;
 struct Args {
     arg_pattern: String,
     arg_file: Vec<String>,
+    flag_count: bool,
 }
 
 fn main() {
@@ -71,10 +75,15 @@ fn run_mmap(args: &Args, searcher: &LineSearcher) -> Result<u64> {
     let mmap = try!(Mmap::open_path(&args.arg_file[0], Protection::Read));
     let text = unsafe { mmap.as_slice() };
     for m in searcher.search(text) {
-        try!(wtr.write(&text[m.start..m.end]));
-        try!(wtr.write(b"\n"));
+        if !args.flag_count {
+            try!(wtr.write(&text[m.start..m.end]));
+            try!(wtr.write(b"\n"));
+        }
         count += 1;
     }
+    if args.flag_count {
+        try!(writeln!(wtr, "{}", count));
+    }
     Ok(count)
 }
 
diff --git a/src/search.rs b/src/search.rs
index d73a9f56..b0933241 100644
--- a/src/search.rs
+++ b/src/search.rs
@@ -125,11 +125,15 @@ impl<'b, 's> Iter<'b, 's> {
     }
 
     fn find_line(&self, s: usize, e: usize) -> (usize, usize) {
-        let prevnl =
-            memrchr(b'\n', &self.buf[0..s]).map_or(0, |i| i + 1);
-        let nextnl =
-            memchr(b'\n', &self.buf[e..]).map_or(self.buf.len(), |i| e + i);
-        (prevnl, nextnl)
+        (self.find_line_start(s), self.find_line_end(e))
+    }
+
+    fn find_line_start(&self, pos: usize) -> usize {
+        memrchr(b'\n', &self.buf[0..pos]).map_or(0, |i| i + 1)
+    }
+
+    fn find_line_end(&self, pos: usize) -> usize {
+        memchr(b'\n', &self.buf[pos..]).map_or(self.buf.len(), |i| pos + i)
     }
 }