From a7e90fb93dce0eaae02f22c01fef34f11377bb60 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Thu, 6 Oct 2022 20:32:26 +0300 Subject: set up hands-on practice Sponsored-by: author --- Cargo.toml | 1 + README.md | 12 ++++++++++++ src/lib.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 8 +++++++- 4 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 README.md create mode 100644 src/lib.rs 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 { + 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(); } + -- cgit v1.2.1