search_buffer.rs 8.7 KB
Newer Older
1 2 3 4 5 6 7 8
/*!
The search_buffer module is responsible for searching a single file all in a
single buffer. Typically, the source of the buffer is a memory map. This can
be useful for when memory maps are faster than streaming search.

Note that this module doesn't quite support everything that search_stream does.
Notably, showing contexts.
*/
A
Andrew Gallant 已提交
9 10 11 12
use std::cmp;
use std::path::Path;

use grep::Grep;
A
Andrew Gallant 已提交
13
use term::Terminal;
A
Andrew Gallant 已提交
14 15

use printer::Printer;
16
use search_stream::{IterLines, Options, count_lines, is_binary};
A
Andrew Gallant 已提交
17 18 19 20 21 22 23 24 25 26 27 28

pub struct BufferSearcher<'a, W: 'a> {
    opts: Options,
    printer: &'a mut Printer<W>,
    grep: &'a Grep,
    path: &'a Path,
    buf: &'a [u8],
    match_count: u64,
    line_count: Option<u64>,
    last_line: usize,
}

A
Andrew Gallant 已提交
29
impl<'a, W: Send + Terminal> BufferSearcher<'a, W> {
A
Andrew Gallant 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    pub fn new(
        printer: &'a mut Printer<W>,
        grep: &'a Grep,
        path: &'a Path,
        buf: &'a [u8],
    ) -> BufferSearcher<'a, W> {
        BufferSearcher {
            opts: Options::default(),
            printer: printer,
            grep: grep,
            path: path,
            buf: buf,
            match_count: 0,
            line_count: None,
            last_line: 0,
        }
    }

    /// If enabled, searching will print a count instead of each match.
    ///
    /// Disabled by default.
    pub fn count(mut self, yes: bool) -> Self {
        self.opts.count = yes;
        self
    }

56 57 58 59 60 61 62 63
    /// If enabled, searching will print the path instead of each match.
    ///
    /// Disabled by default.
    pub fn files_with_matches(mut self, yes: bool) -> Self {
        self.opts.files_with_matches = yes;
        self
    }

A
Andrew Gallant 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    /// Set the end-of-line byte used by this searcher.
    pub fn eol(mut self, eol: u8) -> Self {
        self.opts.eol = eol;
        self
    }

    /// If enabled, matching is inverted so that lines that *don't* match the
    /// given pattern are treated as matches.
    pub fn invert_match(mut self, yes: bool) -> Self {
        self.opts.invert_match = yes;
        self
    }

    /// If enabled, compute line numbers and prefix each line of output with
    /// them.
    pub fn line_number(mut self, yes: bool) -> Self {
        self.opts.line_number = yes;
        self
    }

    /// If enabled, search binary files as if they were text.
    pub fn text(mut self, yes: bool) -> Self {
        self.opts.text = yes;
        self
    }

    #[inline(never)]
    pub fn run(mut self) -> u64 {
        let binary_upto = cmp::min(4096, self.buf.len());
        if !self.opts.text && is_binary(&self.buf[..binary_upto]) {
            return 0;
        }

        self.match_count = 0;
        self.line_count = if self.opts.line_number { Some(0) } else { None };
        let mut last_end = 0;
        for m in self.grep.iter(self.buf) {
            if self.opts.invert_match {
                self.print_inverted_matches(last_end, m.start());
            } else {
                self.print_match(m.start(), m.end());
            }
            last_end = m.end();
107
            if self.printer.is_quiet() || self.opts.files_with_matches {
108 109
                break;
            }
A
Andrew Gallant 已提交
110 111 112 113 114 115 116 117
        }
        if self.opts.invert_match {
            let upto = self.buf.len();
            self.print_inverted_matches(last_end, upto);
        }
        if self.opts.count && self.match_count > 0 {
            self.printer.path_count(self.path, self.match_count);
        }
118 119 120
        if self.opts.files_with_matches && self.match_count > 0 {
            self.printer.path(self.path);
        }
A
Andrew Gallant 已提交
121 122 123 124 125 126
        self.match_count
    }

    #[inline(always)]
    pub fn print_match(&mut self, start: usize, end: usize) {
        self.match_count += 1;
127
        if self.opts.skip_matches() {
A
Andrew Gallant 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
            return;
        }
        self.count_lines(start);
        self.add_line(end);
        self.printer.matched(
            self.grep.regex(), self.path, self.buf,
            start, end, self.line_count);
    }

    #[inline(always)]
    fn print_inverted_matches(&mut self, start: usize, end: usize) {
        debug_assert!(self.opts.invert_match);
        let mut it = IterLines::new(self.opts.eol, start);
        while let Some((s, e)) = it.next(&self.buf[..end]) {
            self.print_match(s, e);
        }
    }

    #[inline(always)]
    fn count_lines(&mut self, upto: usize) {
        if let Some(ref mut line_count) = self.line_count {
            *line_count += count_lines(
                &self.buf[self.last_line..upto], self.opts.eol);
            self.last_line = upto;
        }
    }

    #[inline(always)]
    fn add_line(&mut self, line_end: usize) {
        if let Some(ref mut line_count) = self.line_count {
            *line_count += 1;
            self.last_line = line_end;
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

A
Andrew Gallant 已提交
168 169
    use grep::GrepBuilder;
    use term::{Terminal, TerminfoTerminal};
A
Andrew Gallant 已提交
170

A
Andrew Gallant 已提交
171
    use out::ColoredTerminal;
A
Andrew Gallant 已提交
172 173 174 175
    use printer::Printer;

    use super::BufferSearcher;

A
Andrew Gallant 已提交
176
    const SHERLOCK: &'static str = "\
A
Andrew Gallant 已提交
177 178 179 180 181 182 183
For the Doctor Watsons of this world, as opposed to the Sherlock
Holmeses, success in the province of detective work must always
be, to a very large extent, the result of luck. Sherlock Holmes
can extract a clew from a wisp of straw or a flake of cigar ash;
but Doctor Watson has to have it taken out for him and dusted,
and exhibited clearly, with a label attached.\
";
A
Andrew Gallant 已提交
184

A
Andrew Gallant 已提交
185 186 187 188
    fn test_path() -> &'static Path {
        &Path::new("/baz.rs")
    }

A
Andrew Gallant 已提交
189 190
    type TestSearcher<'a> =
        BufferSearcher<'a, ColoredTerminal<TerminfoTerminal<Vec<u8>>>>;
A
Andrew Gallant 已提交
191 192 193 194 195 196

    fn search<F: FnMut(TestSearcher) -> TestSearcher>(
        pat: &str,
        haystack: &str,
        mut map: F,
    ) -> (u64, String) {
A
Andrew Gallant 已提交
197
        let outbuf = ColoredTerminal::NoColor(vec![]);
A
Andrew Gallant 已提交
198
        let mut pp = Printer::new(outbuf).with_filename(true);
A
Andrew Gallant 已提交
199 200 201 202 203 204
        let grep = GrepBuilder::new(pat).build().unwrap();
        let count = {
            let searcher = BufferSearcher::new(
                &mut pp, &grep, test_path(), haystack.as_bytes());
            map(searcher).run()
        };
205
        (count, String::from_utf8(pp.into_inner().into_inner()).unwrap())
A
Andrew Gallant 已提交
206 207 208 209
    }

    #[test]
    fn basic_search() {
A
Andrew Gallant 已提交
210
        let (count, out) = search("Sherlock", SHERLOCK, |s|s);
A
Andrew Gallant 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        assert_eq!(2, count);
        assert_eq!(out, "\
/baz.rs:For the Doctor Watsons of this world, as opposed to the Sherlock
/baz.rs:be, to a very large extent, the result of luck. Sherlock Holmes
");
    }

    #[test]
    fn binary() {
        let text = "Sherlock\n\x00Holmes\n";
        let (count, out) = search("Sherlock|Holmes", text, |s|s);
        assert_eq!(0, count);
        assert_eq!(out, "");
    }


    #[test]
    fn binary_text() {
        let text = "Sherlock\n\x00Holmes\n";
        let (count, out) = search("Sherlock|Holmes", text, |s| s.text(true));
        assert_eq!(2, count);
        assert_eq!(out, "/baz.rs:Sherlock\n/baz.rs:\x00Holmes\n");
    }

    #[test]
    fn line_numbers() {
        let (count, out) = search(
A
Andrew Gallant 已提交
238
            "Sherlock", SHERLOCK, |s| s.line_number(true));
A
Andrew Gallant 已提交
239 240 241 242 243 244 245 246 247 248
        assert_eq!(2, count);
        assert_eq!(out, "\
/baz.rs:1:For the Doctor Watsons of this world, as opposed to the Sherlock
/baz.rs:3:be, to a very large extent, the result of luck. Sherlock Holmes
");
    }

    #[test]
    fn count() {
        let (count, out) = search(
A
Andrew Gallant 已提交
249
            "Sherlock", SHERLOCK, |s| s.count(true));
A
Andrew Gallant 已提交
250 251 252 253
        assert_eq!(2, count);
        assert_eq!(out, "/baz.rs:2\n");
    }

254 255 256 257 258 259 260 261
    #[test]
    fn files_with_matches() {
        let (count, out) = search(
            "Sherlock", SHERLOCK, |s| s.files_with_matches(true));
        assert_eq!(1, count);
        assert_eq!(out, "/baz.rs\n");
    }

A
Andrew Gallant 已提交
262 263 264
    #[test]
    fn invert_match() {
        let (count, out) = search(
A
Andrew Gallant 已提交
265
            "Sherlock", SHERLOCK, |s| s.invert_match(true));
A
Andrew Gallant 已提交
266 267 268 269 270 271 272 273 274 275 276
        assert_eq!(4, count);
        assert_eq!(out, "\
/baz.rs:Holmeses, success in the province of detective work must always
/baz.rs:can extract a clew from a wisp of straw or a flake of cigar ash;
/baz.rs:but Doctor Watson has to have it taken out for him and dusted,
/baz.rs:and exhibited clearly, with a label attached.
");
    }

    #[test]
    fn invert_match_line_numbers() {
A
Andrew Gallant 已提交
277
        let (count, out) = search("Sherlock", SHERLOCK, |s| {
A
Andrew Gallant 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290
            s.invert_match(true).line_number(true)
        });
        assert_eq!(4, count);
        assert_eq!(out, "\
/baz.rs:2:Holmeses, success in the province of detective work must always
/baz.rs:4:can extract a clew from a wisp of straw or a flake of cigar ash;
/baz.rs:5:but Doctor Watson has to have it taken out for him and dusted,
/baz.rs:6:and exhibited clearly, with a label attached.
");
    }

    #[test]
    fn invert_match_count() {
A
Andrew Gallant 已提交
291
        let (count, out) = search("Sherlock", SHERLOCK, |s| {
A
Andrew Gallant 已提交
292 293 294 295 296 297
            s.invert_match(true).count(true)
        });
        assert_eq!(4, count);
        assert_eq!(out, "/baz.rs:4\n");
    }
}