emojihash/
lib.rs

1#![warn(missing_docs)]
2
3//! emojihash is a library that converts arbitrary byte data to emoji using sha256.
4
5mod consts;
6
7use sha2::{Digest, Sha256};
8
9/// Hashes the input byte array using sha256 and returns a string of the
10/// corresponding emojihash.
11/// 
12/// The conversion only uses the last five bytes of each sha256 hash byte.
13/// Therefore, the amout of char's in the hash is halved, but as emoji are
14/// commonly rendered as double-width characters, the visual length of the
15/// hash is equal to the sha256 hash.
16/// 
17/// ```rust
18/// # use emojihash::hash;
19/// let data = b"My input data";
20/// println!("Hashed data: {}", hash(data));
21/// ```
22/// 
23/// The emoji hashes might seem a bit too long to be *useful*, but if you only
24/// use the first six emoji the amount of possible hashes are still 1073741824.
25pub fn hash(data: &[u8]) -> String {
26    Sha256::digest(data)
27        .iter()
28        .map(|d| {
29            consts::emoji::UTF8_EMOJI[(d & 0b11111) as usize]
30        })
31        .collect()
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn test_hash() {
40        let h1 = hash(&[0b11111_000u8, 0b00_11101_0u8, 0b1010_1010u8]);
41        let h2 = hash(&[0b11111_000u8, 0b00_11101_0u8, 0b1010_1010u8]);
42        let h3 = hash(&[0b11011_000u8, 0b00_11101_0u8, 0b1010_1010u8]);
43        assert_eq!(h1, h2);
44        assert_ne!(h1, h3);
45    }
46}