commit | 6f0d015029eab07f28f2fd09811aa8e4dea7010c | [log] [tgz] |
---|---|---|
author | Xin Li <[email protected]> | Sat Feb 20 13:53:09 2021 +0000 |
committer | Automerger Merge Worker <[email protected]> | Sat Feb 20 13:53:09 2021 +0000 |
tree | 6dbbba641a2d90f06fdc582379a9d43be23e930f | |
parent | d324380d73c00a3273b80e1992aa69b15799c1ad [diff] | |
parent | e362c7d55fee88794fe66b261fcfa656aa4b226d [diff] |
[automerger skipped] Mark ab/7061308 as merged in stage. am: e451404f0c -s ours am: e362c7d55f -s ours am skip reason: Change-Id I0f78ad7bf0ad839f026c89bca1521fd6a726dae3 with SHA-1 7bf11c94b4 is in history Original change: undetermined MUST ONLY BE SUBMITTED BY AUTOMERGER Change-Id: I92b8dd3635d11c60ae50e050dd0218b215c2fd7e
An implementation of the Fowler–Noll–Vo hash function.
The FNV hash function is a custom Hasher
implementation that is more efficient for smaller hash keys.
The Rust FAQ states that while the default Hasher
implementation, SipHash, is good in many cases, it is notably slower than other algorithms with short keys, such as when you have a map of integers to other values. In cases like these, FNV is demonstrably faster.
Its disadvantages are that it performs badly on larger inputs, and provides no protection against collision attacks, where a malicious user can craft specific keys designed to slow a hasher down. Thus, it is important to profile your program to ensure that you are using small hash keys, and be certain that your program could not be exposed to malicious inputs (including being a networked server).
The Rust compiler itself uses FNV, as it is not worried about denial-of-service attacks, and can assume that its inputs are going to be small—a perfect use case for FNV.
To include this crate in your program, add the following to your Cargo.toml
:
[dependencies] fnv = "1.0.3"
The FnvHashMap
type alias is the easiest way to use the standard library’s HashMap
with FNV.
use fnv::FnvHashMap; let mut map = FnvHashMap::default(); map.insert(1, "one"); map.insert(2, "two"); map = FnvHashMap::with_capacity_and_hasher(10, Default::default()); map.insert(1, "one"); map.insert(2, "two");
Note, the standard library’s HashMap::new
and HashMap::with_capacity
are only implemented for the RandomState
hasher, so using Default
to get the hasher is the next best option.
Similarly, FnvHashSet
is a type alias for the standard library’s HashSet
with FNV.
use fnv::FnvHashSet; let mut set = FnvHashSet::default(); set.insert(1); set.insert(2); set = FnvHashSet::with_capacity_and_hasher(10, Default::default()); set.insert(1); set.insert(2);