summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLars Wirzenius <liw@sequoia-pgp.org>2022-10-06 20:32:26 +0300
committerLars Wirzenius <liw@sequoia-pgp.org>2022-10-06 20:32:26 +0300
commita7e90fb93dce0eaae02f22c01fef34f11377bb60 (patch)
tree8840e550e8f26b0caa7f8e4d83ad3362da1c7752
parent615f65c26eb4283b7cba5fb72937e7f623ff789a (diff)
downloadchecksums-hands-on-a7e90fb93dce0eaae02f22c01fef34f11377bb60.tar.gz
set up hands-on practice
Sponsored-by: author
-rw-r--r--Cargo.toml1
-rw-r--r--README.md12
-rw-r--r--src/lib.rs44
-rw-r--r--src/main.rs8
4 files changed, 64 insertions, 1 deletions
diff --git a/Cargo.toml b/Cargo.toml
index 3b67d9a..19abfe0 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,3 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+sha2 = "0.10.2"
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..35c0b07
--- /dev/null
+++ b/README.md
@@ -0,0 +1,12 @@
+Your mission, should you choose to accept it, is to edit `src/main.rs`
+so that it works like this:
+
+~~~sh
+cargo run -- Cargo.toml README.md
+~~~
+
+The output should be identical to the output of the following command:
+
+~~~sh
+sha256sum Cargo.toml README.md
+~~~
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..93627f1
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,44 @@
+use sha2::{Digest, Sha256};
+use std::fs::File;
+use std::io::{BufReader, Read};
+use std::path::{Path, PathBuf};
+
+const BUF_SIZE: usize = 4096;
+
+#[derive(Debug)]
+pub struct FileChecksum {
+ pub filename: PathBuf,
+ pub checksum: String,
+}
+
+impl FileChecksum {
+ pub fn new(filename: &Path, checksum: String) -> Self {
+ Self {
+ filename: filename.to_path_buf(),
+ checksum,
+ }
+ }
+
+ pub fn print(&self) {
+ println!("{} {}", self.checksum, self.filename.display());
+ }
+}
+
+pub fn checksum(filename: &Path) -> Result<FileChecksum, std::io::Error> {
+ let mut checksum = Sha256::new();
+
+ let file = File::open(filename)?;
+ let mut reader = BufReader::new(file);
+ loop {
+ let mut buf = vec![0; BUF_SIZE];
+ let n = reader.read(&mut buf)?;
+ if n == 0 {
+ break;
+ }
+ checksum.update(&buf[..n]);
+ }
+
+ let checksum = checksum.finalize();
+ let checksum = format!("{checksum:x}");
+ Ok(FileChecksum::new(filename, checksum))
+}
diff --git a/src/main.rs b/src/main.rs
index e7a11a9..155c9e9 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,9 @@
+mod lib;
+use lib::checksum;
+use std::path::Path;
+
fn main() {
- println!("Hello, world!");
+ let sum = checksum(Path::new("Cargo.toml")).unwrap();
+ sum.print();
}
+