diff --git a/rust-handson/rsgrep/.gitignore b/rust-handson/rsgrep/.gitignore new file mode 100644 index 0000000..64f3e54 --- /dev/null +++ b/rust-handson/rsgrep/.gitignore @@ -0,0 +1,18 @@ +### https://raw.github.com/github/gitignore/3bb7b4b767f3f8df07e362dfa03c8bd425f16d32/Rust.gitignore + +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + + diff --git a/rust-handson/rsgrep/Cargo.toml b/rust-handson/rsgrep/Cargo.toml new file mode 100644 index 0000000..cdc51e6 --- /dev/null +++ b/rust-handson/rsgrep/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "rsgrep" +version = "0.1.0" +authors = ["Shingo Yamazaki "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rayon = "1.5.1" +structopt = "0.3.22" diff --git a/rust-handson/rsgrep/src/main.rs b/rust-handson/rsgrep/src/main.rs new file mode 100644 index 0000000..df192f9 --- /dev/null +++ b/rust-handson/rsgrep/src/main.rs @@ -0,0 +1,34 @@ +use rayon::prelude::*; +use std::{env::args, fs::read_to_string}; +use structopt::StructOpt; + +#[derive(StructOpt)] +#[structopt(name = "rsgrep")] +struct GrepArgs { + #[structopt(name = "PATTERN")] + pattern: String, + #[structopt(name = "FILE")] + path: Vec, +} + +fn grep(state: &GrepArgs, content: String, file_name: &str) { + for line in content.lines() { + if line.contains(state.pattern.as_str()) { + println!("{}: {}", file_name, line); + } + } +} + +fn run(state: GrepArgs) { + state + .path + .par_iter() + .for_each(|file| match read_to_string(file) { + Ok(content) => grep(&state, content, file), + Err(reason) => println!("{}", reason), + }); +} + +fn main() { + run(GrepArgs::from_args()); +}