Skip to main content

sendmock_core/
file_checksums.rs

1//! The checksums mail tools show for a file, as lowercase hex.
2
3use md5::Md5;
4use sha1::Sha1;
5use sha2::{Digest, Sha256};
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct FileChecksums {
9    pub md5: String,
10    pub sha1: String,
11    pub sha256: String,
12}
13
14fn write_hex(digest_bytes: &[u8]) -> String {
15    digest_bytes
16        .iter()
17        .map(|byte| format!("{byte:02x}"))
18        .collect()
19}
20
21pub fn compute_file_checksums(file_bytes: &[u8]) -> FileChecksums {
22    FileChecksums {
23        md5: write_hex(&Md5::digest(file_bytes)),
24        sha1: write_hex(&Sha1::digest(file_bytes)),
25        sha256: write_hex(&Sha256::digest(file_bytes)),
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32
33    #[test]
34    fn the_checksums_of_a_known_text_match_the_published_values() {
35        let checksums = compute_file_checksums(b"abc");
36
37        assert_eq!(checksums.md5, "900150983cd24fb0d6963f7d28e17f72");
38        assert_eq!(checksums.sha1, "a9993e364706816aba3e25717850c26c9cd0d89d");
39        assert_eq!(
40            checksums.sha256,
41            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
42        );
43    }
44}