sugars/
hash.rs

1/// Macro that return the hash of what is passed and also can receive
2/// a hasher to use that intead of default [`HashMap`] Hasher.
3///
4/// # Example
5/// ```
6/// # use std::collections::hash_map::DefaultHasher;
7/// # use sugars::hash;
8/// # fn main() {
9/// // No Hasher
10/// let hash = hash!("a");
11/// assert_eq!(8_186_225_505_942_432_243, hash);
12///
13/// // With Hasher
14/// let hash = hash!("b", DefaultHasher::new());
15/// assert_eq!(16_993_177_596_579_750_922, hash);
16/// # }
17/// ```
18///
19/// [`HashMap`]: ::std::collections::HashMap
20#[macro_export]
21macro_rules! hash {
22    ($e:expr) => {{
23        use ::std::{
24            collections::hash_map::DefaultHasher,
25            hash::{Hash, Hasher},
26        };
27        let mut hasher = DefaultHasher::new();
28        $e.hash(&mut hasher);
29        hasher.finish()
30    }};
31
32    ($e:expr, $hasher:expr) => {{
33        use ::std::hash::{Hash, Hasher};
34        let mut hasher = $hasher;
35        $e.hash(&mut hasher);
36        hasher.finish()
37    }};
38}
39
40#[cfg(test)]
41mod tests {
42    use std::collections::hash_map::DefaultHasher;
43
44    #[test]
45    fn hash_default() {
46        let a = "b";
47        let expected = 16_993_177_596_579_750_922;
48        let test = hash!(a);
49
50        assert_eq!(expected, test);
51    }
52
53    #[test]
54    fn hash_with_hasher() {
55        let a = "b";
56        let expected = 16_993_177_596_579_750_922;
57        let test = hash!(a, DefaultHasher::new());
58
59        assert_eq!(expected, test);
60    }
61}