Skip to content

Instantly share code, notes, and snippets.

@gandro
Created October 15, 2017 21:12
Show Gist options
  • Save gandro/c7ed4e47fa9eae4fdb8ac67ebc713d16 to your computer and use it in GitHub Desktop.
Save gandro/c7ed4e47fa9eae4fdb8ac67ebc713d16 to your computer and use it in GitHub Desktop.
poorgrep
[package]
authors = ["Sebastian Wicki <gandro@gmx.net>"]
name = "poorgrep"
version = "0.1.0"
[dependencies]
grep = "0.1.6"
ignore = "0.2.2"
memmap = "0.5.2"
extern crate memmap;
extern crate ignore;
extern crate grep;
use memmap::{Mmap, Protection};
use ignore::{WalkBuilder, WalkState};
use grep::{Grep, GrepBuilder};
use std::io::Result;
use std::path::Path;
fn search_file(file: &Path, pattern: &Grep) -> Result<()> {
let file_mmap = Mmap::open_path(file, Protection::Read)?;
let bytes = unsafe { file_mmap.as_slice() };
for m in pattern.iter(bytes) {
let line = &bytes[m.start()..m.end()];
println!("Match found in file {:?}: {:?}", file, String::from_utf8_lossy(&line))
}
Ok(())
}
fn main() {
let pattern = GrepBuilder::new("foo").build().expect("invalid pattern");
let files = WalkBuilder::new("./").build_parallel();
files.run(|| {
let pattern = pattern.clone();
Box::new(move |entry| {
let dir_entry = entry.expect("failed to walk files");
if dir_entry.file_type().map(|e| e.is_file()).unwrap_or(false) {
search_file(dir_entry.path(), &pattern).expect("grepping file failed");
}
WalkState::Continue
})
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment