scsys_crypto/hash/
mod.rs

1/*
2    Appellation: hash <module>
3    Contributors: FL03 <jo3mccain@icloud.com>
4    Description: ... Summary ...
5*/
6pub use self::{hasher::Hash, hashes::*, utils::*};
7
8pub(crate) mod hasher;
9pub(crate) mod hashes;
10
11pub(crate) mod utils {
12    use crate::GenericHash;
13    use std::string::ToString;
14
15    /// hasher implements a generic hash function wrapper around blake3
16    pub fn hasher<T: ToString>(data: &T) -> GenericHash {
17        blake3::hash(data.to_string().as_bytes())
18            .as_bytes()
19            .to_owned()
20            .into()
21    }
22    /// Given a collection of elements, reduce into a single hash by updating the same hasher
23    pub fn iter_hasher<T: ToString>(data: &Vec<T>) -> GenericHash {
24        let mut hasher = blake3::Hasher::default();
25        for i in data {
26            hasher.update(i.to_string().as_bytes());
27        }
28        hasher.finalize().as_bytes().to_owned().into()
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35    use rand::{self, distributions::Alphanumeric, Rng};
36
37    pub fn generate_random_string(length: Option<usize>) -> String {
38        std::ops::Range {
39            start: 0,
40            end: length.unwrap_or(12),
41        }
42        .map(|_| rand::thread_rng().sample(Alphanumeric) as char)
43        .collect::<String>()
44    }
45
46    #[test]
47    fn test_hasher() {
48        let a = hasher(&generate_random_string(None));
49        let b = hasher(&generate_random_string(None));
50        assert_ne!(&a, &b)
51    }
52
53    #[test]
54    fn test_iter_hasher() {
55        let hashes = |i: usize| {
56            std::ops::Range { start: 0, end: i }
57                .map(|_| generate_random_string(None))
58                .collect::<Vec<String>>()
59        };
60        let a = iter_hasher(&hashes(10));
61        let b = iter_hasher(&hashes(12));
62        assert_ne!(&a, &b)
63    }
64}