amazon_cloudfront_client_routing_lib/
hash.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::hash::Hasher;
5use twox_hash::XxHash64;
6
7/// Utilizes xxHash to hash a `cgid` into a 64 bit number and returns that
8/// number.
9///
10/// Passing an empty string as the `cgid` will result in 0 being returned
11/// instead of the hash of `cgid`.
12///
13/// # Examples
14/// ```
15/// use amazon_cloudfront_client_routing_lib::hash::hash_cgid;
16///
17/// // valid cgid
18/// let mut hashed_cgid = hash_cgid("f3663718-7699-4e6e-b482-daa2f690cf64");
19/// assert_eq!(8517775255794402596, hashed_cgid);
20///
21/// // empty cgid
22/// hashed_cgid = hash_cgid("");
23/// assert_eq!(0, hashed_cgid);
24/// ```
25pub fn hash_cgid(cgid: &str) -> u64 {
26    if cgid.is_empty() {
27        return 0;
28    }
29
30    let mut hasher = XxHash64::default();
31    hasher.write(cgid.as_bytes());
32
33    hasher.finish()
34}
35
36#[cfg(test)]
37mod tests {
38    use super::hash_cgid;
39
40    #[test]
41    fn validate_hash_cgid() {
42        assert_eq!(9402033733208250942, hash_cgid("SM89P"));
43        assert_eq!(16745045142164894816, hash_cgid("DP0124QHYT"));
44        assert_eq!(15007018045908736946, hash_cgid("b086vx9VmK"));
45        assert_eq!(15151312625956013430, hash_cgid("abcdefghijhjuio"));
46        assert_eq!(
47            8696017447135811798,
48            hash_cgid("VZ9C5G6H12PC5GH7Y0ABCDEFGHIJHJUIOZZAA1")
49        );
50    }
51
52    #[test]
53    fn validate_hash_similar_cgids_not_equal() {
54        assert_ne!(hash_cgid("SM89P"), hash_cgid("sm89p"));
55        assert_ne!(hash_cgid("abcdefghijhjuio0"), hash_cgid("abcdefghijhjuio"));
56        assert_ne!(hash_cgid("B086VX9VMK "), hash_cgid("B086VX9VMK"));
57        assert_ne!(
58            hash_cgid("hfquwah9tds\u{00}"),
59            hash_cgid("hfquwah9tds\u{01}")
60        );
61    }
62
63    #[test]
64    fn validate_hash_empty_cgid_zero() {
65        assert_eq!(0, hash_cgid(""));
66    }
67}