ixa/
hashing.rs

1//! This module provides a deterministic hasher and `HashMap` and `HashSet` variants that use
2//! it. The hashing data structures in the standard library are not deterministic:
3//!
4//! > By default, HashMap uses a hashing algorithm selected to provide
5//! > resistance against HashDoS attacks. The algorithm is randomly seeded, and a
6//! > reasonable best-effort is made to generate this seed from a high quality,
7//! > secure source of randomness provided by the host without blocking the program.
8//!
9//! The standard library `HashMap` has a `new` method, but `HashMap<K, V, S>` does not have a `new`
10//! method by default. Use `HashMap::default()` instead to create a new hashmap with the default
11//! hasher. If you really need to keep the API the same across implementations, we provide the
12//! `HashMapExt` trait extension. Similarly, for `HashSet` and `HashSetExt`.The traits need only be
13//! in scope.
14//!
15//! The `hash_usize` free function is a convenience function used in `crate::random::get_rng`.
16
17pub use rustc_hash::FxHashMap as HashMap;
18pub use rustc_hash::FxHashSet as HashSet;
19use std::hash::Hasher;
20
21/// Provides API parity with `std::collections::HashMap`.
22pub trait HashMapExt {
23    fn new() -> Self;
24}
25
26impl<K, V> HashMapExt for HashMap<K, V> {
27    fn new() -> Self {
28        HashMap::default()
29    }
30}
31
32// Note that trait aliases are not yet stabilized in rustc.
33// See https://github.com/rust-lang/rust/issues/41517
34/// Provides API parity with `std::collections::HashSet`.
35pub trait HashSetExt {
36    fn new() -> Self;
37}
38
39impl<T> HashSetExt for HashSet<T> {
40    fn new() -> Self {
41        HashSet::default()
42    }
43}
44
45/// A convenience method to compute the hash of a `&str`.
46pub fn hash_str(data: &str) -> u64 {
47    let mut hasher = rustc_hash::FxHasher::default();
48    hasher.write(data.as_bytes());
49    hasher.finish()
50}