fhc 0.12.0

File hash checker (BLAKE3, SHA256, SHA512)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use {
    anyhow::{Result, anyhow},
    clap::ValueEnum,
    rayon::prelude::*,
    sha2::{Digest, Sha256, Sha512, digest::DynDigest},
    std::{
        fmt::Write as _,
        fs::File,
        io::{BufRead, BufReader, Read, Write, copy},
        path::Path,
    },
};

#[cfg(test)]
mod tests;

const BUFFER_SIZE: usize = 4096;

/// Hash algorithm
#[derive(Clone, Copy, Debug, clap::ValueEnum)]
pub enum Hash {
    Blake3,
    Sha256,
    Sha512,
    Blake3Sha256,
    Blake3Sha512,
    Sha256Sha512,
    All,
}

impl Hash {
    /**
    Hash a file and return the hash(es) as `(ckfile, hash)` tuples

    # Errors

    Returns an error if not able to read the given file
    */
    pub fn hash_file<P: AsRef<Path>>(&self, file: P) -> Result<Vec<(String, String)>> {
        match self {
            Hash::Blake3 => file_blake3(file),
            Hash::Sha256 => file_sha256(file),
            Hash::Sha512 => file_sha512(file),
            Hash::Blake3Sha256 => file_blake3_sha256(file),
            Hash::Blake3Sha512 => file_blake3_sha512(file),
            Hash::Sha256Sha512 => file_sha256_sha512(file),
            Hash::All => file_all(file),
        }
    }

    /**
    Process a file

    If the hash file exists, hash the file, compare hashes, and return the result.

    If the hash file does not exist, hash the file, save the hash file, and return the result.

    # Errors

    Returns an error if not able to process the given file
    */
    #[allow(clippy::missing_panics_doc)]
    pub fn process_file<P: AsRef<Path>>(&self, file: P) -> Result<String> {
        let file = file.as_ref();

        // Calculate the hashes
        let hashes = self.hash_file(file)?;

        Ok(if let Ok(expected) = self.expected(file) {
            // The hash file(s) exist, so verify them and return the result.
            format!(
                "{}: {}",
                file.display(),
                if hashes == expected { "OK" } else { "FAILED" },
            )
        } else {
            // The hash file(s) do not exist, so save the hash(es) to new hash file(s), and return it.
            let mut r = vec![];
            for (ckfile, hash) in &hashes {
                let mut ckfile = File::create(ckfile)?;
                let filename = file.file_name().unwrap().to_str().unwrap();
                let content = format!("{hash}  {filename}\n");
                ckfile.write_all(content.as_bytes())?;
                r.push(format!("{hash}  {}", file.display()));
            }
            r.join("\n")
        })
    }

    /**
    Get the expected hash(es) from hash file(s)

    # Panics

    Panics if not able to get the expected hash from the hash file(s)

    # Errors

    Returns an error if not able to get the expected hash from the hash file(s)
    */
    pub fn expected<P: AsRef<Path>>(&self, file: P) -> Result<Vec<(String, String)>> {
        let file = file.as_ref();

        let mut r = vec![];

        let ckfiles = match self {
            Hash::Blake3 => vec![format!("{}.b3", file.display())],
            Hash::Sha256 => vec![format!("{}.sha256", file.display())],
            Hash::Sha512 => vec![format!("{}.sha512", file.display())],
            Hash::Blake3Sha256 => vec![
                format!("{}.b3", file.display()),
                format!("{}.sha256", file.display()),
            ],
            Hash::Blake3Sha512 => vec![
                format!("{}.b3", file.display()),
                format!("{}.sha512", file.display()),
            ],
            Hash::Sha256Sha512 => vec![
                format!("{}.sha256", file.display()),
                format!("{}.sha512", file.display()),
            ],
            Hash::All => vec![
                format!("{}.b3", file.display()),
                format!("{}.sha256", file.display()),
                format!("{}.sha512", file.display()),
            ],
        };

        for ckfile in ckfiles {
            let mut reader = BufReader::new(File::open(&ckfile)?);
            let mut expected = String::new();
            reader.read_line(&mut expected)?;
            expected = expected.lines().next().unwrap().to_string();
            expected.truncate(expected.find(' ').unwrap_or(expected.len()));
            r.push((ckfile, expected));
        }

        Ok(r)
    }
}

/**
Calculate the SHA256 hash for a file

# Errors

Returns an error if not able to read the given file
*/
pub fn file_sha256<P: AsRef<Path>>(file: P) -> Result<Vec<(String, String)>> {
    let file = file.as_ref();
    let mut f = BufReader::new(File::open(file)?);
    let mut hasher = Sha256::new();
    let mut buffer = [0; BUFFER_SIZE];
    loop {
        let bytes_read = f.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }
        Digest::update(&mut hasher, &buffer[..bytes_read]);
    }
    let mut buffer = vec![0; hasher.output_size()];
    DynDigest::finalize_into(hasher, &mut buffer)?;
    let hash = to_hex_string(&buffer);
    Ok(vec![(
        format!("{}.sha256", file.display()),
        format!("SHA256:{hash}"),
    )])
}

/**
Calculate the SHA512 hash for a file

# Errors

Returns an error if not able to read the given file
*/
pub fn file_sha512<P: AsRef<Path>>(file: P) -> Result<Vec<(String, String)>> {
    let file = file.as_ref();
    let mut f = File::open(file)?;
    let mut hasher = Sha512::new();
    let mut buffer = [0; BUFFER_SIZE];
    loop {
        let bytes_read = f.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }
        Digest::update(&mut hasher, &buffer[..bytes_read]);
    }
    let mut buffer = vec![0; hasher.output_size()];
    DynDigest::finalize_into(hasher, &mut buffer)?;
    let hash = to_hex_string(&buffer);
    Ok(vec![(
        format!("{}.sha512", file.display()),
        format!("SHA512:{hash}"),
    )])
}

/**
Calculate the BLAKE3 hash for a file

# Errors

Returns an error if not able to read the given file
*/
pub fn file_blake3<P: AsRef<Path>>(file: P) -> Result<Vec<(String, String)>> {
    let file = file.as_ref();
    let mut f = File::open(file)?;
    let mut hasher = blake3::Hasher::new();
    copy(&mut f, &mut hasher)?;
    Ok(vec![(
        format!("{}.b3", file.display()),
        format!("BLAKE3:{}", hasher.finalize()),
    )])
}

/**
Calculate the BLAKE3 and SHA256 hashes for a file

# Errors

Returns an error if not able to read the given file
*/
pub fn file_blake3_sha256<P: AsRef<Path>>(file: P) -> Result<Vec<(String, String)>> {
    let file = file.as_ref();
    let mut f = File::open(file)?;

    let mut hasher_b3 = blake3::Hasher::new();
    let mut hasher_sha256 = Sha256::new();

    let mut buffer = [0; BUFFER_SIZE];
    loop {
        let bytes_read = f.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }
        let buf = &buffer[..bytes_read];
        hasher_b3.update(buf);
        Digest::update(&mut hasher_sha256, buf);
    }

    let mut buffer = vec![0; hasher_sha256.output_size()];
    DynDigest::finalize_into(hasher_sha256, &mut buffer)?;
    let hash_sha256 = to_hex_string(&buffer);

    Ok(vec![
        (
            format!("{}.b3", file.display()),
            format!("BLAKE3:{}", hasher_b3.finalize()),
        ),
        (
            format!("{}.sha256", file.display()),
            format!("SHA256:{hash_sha256}"),
        ),
    ])
}

/**
Calculate the BLAKE3 and SHA512 hashes for a file

# Errors

Returns an error if not able to read the given file
*/
pub fn file_blake3_sha512<P: AsRef<Path>>(file: P) -> Result<Vec<(String, String)>> {
    let file = file.as_ref();
    let mut f = File::open(file)?;

    let mut hasher_b3 = blake3::Hasher::new();
    let mut hasher_sha512 = Sha512::new();

    let mut buffer = [0; BUFFER_SIZE];
    loop {
        let bytes_read = f.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }
        let buf = &buffer[..bytes_read];
        hasher_b3.update(buf);
        Digest::update(&mut hasher_sha512, buf);
    }

    let mut buffer = vec![0; hasher_sha512.output_size()];
    DynDigest::finalize_into(hasher_sha512, &mut buffer)?;
    let hash_sha512 = to_hex_string(&buffer);

    Ok(vec![
        (
            format!("{}.b3", file.display()),
            format!("BLAKE3:{}", hasher_b3.finalize()),
        ),
        (
            format!("{}.sha512", file.display()),
            format!("SHA512:{hash_sha512}"),
        ),
    ])
}

/**
Calculate the SHA256 and SHA512 hashes for a file

# Errors

Returns an error if not able to read the given file
*/
pub fn file_sha256_sha512<P: AsRef<Path>>(file: P) -> Result<Vec<(String, String)>> {
    let file = file.as_ref();
    let mut f = File::open(file)?;

    let mut hasher_sha256 = Sha256::new();
    let mut hasher_sha512 = Sha512::new();

    let mut buffer = [0; BUFFER_SIZE];
    loop {
        let bytes_read = f.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }
        let buf = &buffer[..bytes_read];
        Digest::update(&mut hasher_sha256, buf);
        Digest::update(&mut hasher_sha512, buf);
    }

    let mut buffer = vec![0; hasher_sha256.output_size()];
    DynDigest::finalize_into(hasher_sha256, &mut buffer)?;
    let hash_sha256 = to_hex_string(&buffer);

    let mut buffer = vec![0; hasher_sha512.output_size()];
    DynDigest::finalize_into(hasher_sha512, &mut buffer)?;
    let hash_sha512 = to_hex_string(&buffer);

    Ok(vec![
        (
            format!("{}.sha256", file.display()),
            format!("SHA256:{hash_sha256}"),
        ),
        (
            format!("{}.sha512", file.display()),
            format!("SHA512:{hash_sha512}"),
        ),
    ])
}

/**
Calculate all hashes for a file

# Errors

Returns an error if not able to read the given file
*/
pub fn file_all<P: AsRef<Path>>(file: P) -> Result<Vec<(String, String)>> {
    let file = file.as_ref();
    let mut f = File::open(file)?;

    let mut hasher_b3 = blake3::Hasher::new();
    let mut hasher_sha256 = Sha256::new();
    let mut hasher_sha512 = Sha512::new();

    let mut buffer = [0; BUFFER_SIZE];
    loop {
        let bytes_read = f.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }
        let buf = &buffer[..bytes_read];
        hasher_b3.update(buf);
        Digest::update(&mut hasher_sha256, buf);
        Digest::update(&mut hasher_sha512, buf);
    }

    let mut buffer = vec![0; hasher_sha256.output_size()];
    DynDigest::finalize_into(hasher_sha256, &mut buffer)?;
    let hash_sha256 = to_hex_string(&buffer);

    let mut buffer = vec![0; hasher_sha512.output_size()];
    DynDigest::finalize_into(hasher_sha512, &mut buffer)?;
    let hash_sha512 = to_hex_string(&buffer);

    Ok(vec![
        (
            format!("{}.b3", file.display()),
            format!("BLAKE3:{}", hasher_b3.finalize()),
        ),
        (
            format!("{}.sha256", file.display()),
            format!("SHA256:{hash_sha256}"),
        ),
        (
            format!("{}.sha512", file.display()),
            format!("SHA512:{hash_sha512}"),
        ),
    ])
}

/// Approaches for processing multiple files
#[derive(Clone, Debug, ValueEnum)]
pub enum ProcessOption {
    RayonParIter,
    SequentialForLoop,
    SequentialIter,
    Threading,
    Messaging,
}

impl ProcessOption {
    /// Process files with the given hash
    pub fn run<P: AsRef<Path> + Clone + Send + Sync + 'static>(
        &self,
        files: &[P],
        hash: Hash,
    ) -> Vec<Result<String>> {
        match self {
            ProcessOption::SequentialForLoop => seq_for_loop(files, hash),
            ProcessOption::SequentialIter => seq_iter(files, hash),
            ProcessOption::Threading => threading(files, hash),
            ProcessOption::Messaging => messaging(files, hash),
            ProcessOption::RayonParIter => rayon_par_iter(files, hash),
        }
    }
}

/// Process files with the given hash algorithm via seqential for loop
pub fn seq_for_loop<P: AsRef<Path> + Clone + Send + Sync + 'static>(
    files: &[P],
    hash: Hash,
) -> Vec<Result<String>> {
    let mut r = vec![];
    for file in files {
        r.push(hash.process_file(file));
    }
    r
}

/// Process files with the given hash algorithm via seqential iterator
pub fn seq_iter<P: AsRef<Path> + Clone + Send + Sync + 'static>(
    files: &[P],
    hash: Hash,
) -> Vec<Result<String>> {
    files.iter().map(|file| hash.process_file(file)).collect()
}

/// Process files with the given hash algorithm via threading
pub fn threading<P: AsRef<Path> + Clone + Send + Sync + 'static>(
    files: &[P],
    hash: Hash,
) -> Vec<Result<String>> {
    let mut r = vec![];
    let mut handles = vec![];
    for file in files.iter().cloned() {
        handles.push(std::thread::spawn(move || hash.process_file(file)));
    }
    for handle in handles {
        match handle.join() {
            Ok(t) => {
                r.push(t);
            }
            Err(e) => {
                r.push(Err(anyhow!(format!("{e:?}"))));
            }
        }
    }
    r
}

/**
Process files with the given hash algorithm via messaging

# Panics

Panics if not able to spawn a thread
*/
pub fn messaging<P: AsRef<Path> + Clone + Send + Sync + 'static>(
    files: &[P],
    hash: Hash,
) -> Vec<Result<String>> {
    let mut r = vec![];
    let mut rxs = vec![];
    for file in files.iter().cloned() {
        let (tx, rx) = std::sync::mpsc::channel();
        rxs.push(rx);
        std::thread::spawn(move || tx.send(hash.process_file(file)).unwrap());
    }
    for rx in rxs {
        match rx.recv() {
            Ok(t) => {
                r.push(t);
            }
            Err(e) => {
                r.push(Err(anyhow!(format!("{e:?}"))));
            }
        }
    }
    r
}

/// Process files with the given hash algorithm via Rayon parallel iterator
pub fn rayon_par_iter<P: AsRef<Path> + Clone + Send + Sync + 'static>(
    files: &[P],
    hash: Hash,
) -> Vec<Result<String>> {
    files
        .par_iter()
        .map(|file| hash.process_file(file))
        .collect()
}

/// Convert a finalized hash to a hex string
fn to_hex_string(buffer: &[u8]) -> String {
    buffer.iter().fold(String::new(), |mut output, b| {
        let _ = write!(output, "{b:02x}");
        output
    })
}