summaryrefslogtreecommitdiff
path: root/examples/recursive-sha256/src
diff options
context:
space:
mode:
authorStefan Kreutz <mail@skreutz.com>2022-12-19 18:02:18 +0100
committerStefan Kreutz <mail@skreutz.com>2022-12-19 18:02:18 +0100
commita7213ed931f2504902c3d7378d4423a9984f8635 (patch)
treefbfa2fd079407fb55b532ba18bd875e003a1383c /examples/recursive-sha256/src
parent9f83f904d490e64306f1f288234221aab9d57dd9 (diff)
downloadparseq-a7213ed931f2504902c3d7378d4423a9984f8635.tar
Add recursive SHA256 example application
Diffstat (limited to 'examples/recursive-sha256/src')
-rw-r--r--examples/recursive-sha256/src/main.rs55
1 files changed, 55 insertions, 0 deletions
diff --git a/examples/recursive-sha256/src/main.rs b/examples/recursive-sha256/src/main.rs
new file mode 100644
index 0000000..6fcbbfa
--- /dev/null
+++ b/examples/recursive-sha256/src/main.rs
@@ -0,0 +1,55 @@
+//! Print the SHA256 sum of each regular file in the current directory recursively.
+
+use std::{fs::File, path::PathBuf};
+
+use parseq::ParallelIterator;
+use sha2::{Digest, Sha256};
+use walkdir::WalkDir;
+
+fn main() {
+ WalkDir::new(".")
+ .sort_by_file_name()
+ .into_iter()
+ .filter_map(|entry| match entry {
+ Ok(entry) if entry.file_type().is_file() => Some(Ok(entry.into_path())),
+ Ok(_) => None,
+ Err(err) => Some(Err(Error::WalkdirError(err))),
+ })
+ .map_parallel(|item| {
+ item.and_then(|path| {
+ let mut file =
+ File::open(&path).map_err(|err| Error::IoError(path.clone(), err))?;
+ let mut hasher = Sha256::new();
+ std::io::copy(&mut file, &mut hasher)
+ .map_err(|err| Error::IoError(path.clone(), err))?;
+ Ok((path, hasher.finalize()))
+ })
+ })
+ .for_each(|item| match item {
+ Ok((path, hash)) => println!("{:x} {}", hash, path.display()),
+ Err(err) => eprintln!("{err}"),
+ });
+}
+
+#[derive(Debug)]
+enum Error {
+ WalkdirError(walkdir::Error),
+ IoError(PathBuf, std::io::Error),
+}
+
+impl std::error::Error for Error {}
+
+impl std::fmt::Display for Error {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Error::WalkdirError(err) => {
+ if let Some(path) = err.path() {
+ write!(f, "{}: {}", path.display(), err)
+ } else {
+ write!(f, "{err}")
+ }
+ }
+ Error::IoError(path, err) => write!(f, "{}: {}", path.display(), err),
+ }
+ }
+}
Generated by cgit. See skreutz.com for my tech blog and contact information.