]> git.proxmox.com Git - rustc.git/blob - vendor/sha2/examples/sha256sum.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / vendor / sha2 / examples / sha256sum.rs
1 use sha2::{Digest, Sha256};
2 use std::env;
3 use std::fs;
4 use std::io::{self, Read};
5
6 const BUFFER_SIZE: usize = 1024;
7
8 /// Print digest result as hex string and name pair
9 fn print_result(sum: &[u8], name: &str) {
10 for byte in sum {
11 print!("{:02x}", byte);
12 }
13 println!("\t{}", name);
14 }
15
16 /// Compute digest value for given `Reader` and print it
17 /// On any error simply return without doing anything
18 fn process<D: Digest + Default, R: Read>(reader: &mut R, name: &str) {
19 let mut sh = D::default();
20 let mut buffer = [0u8; BUFFER_SIZE];
21 loop {
22 let n = match reader.read(&mut buffer) {
23 Ok(n) => n,
24 Err(_) => return,
25 };
26 sh.update(&buffer[..n]);
27 if n == 0 || n < BUFFER_SIZE {
28 break;
29 }
30 }
31 print_result(&sh.finalize(), name);
32 }
33
34 fn main() {
35 let args = env::args();
36 // Process files listed in command line arguments one by one
37 // If no files provided process input from stdin
38 if args.len() > 1 {
39 for path in args.skip(1) {
40 if let Ok(mut file) = fs::File::open(&path) {
41 process::<Sha256, _>(&mut file, &path);
42 }
43 }
44 } else {
45 process::<Sha256, _>(&mut io::stdin(), "-");
46 }
47 }