8 stable releases

Uses old Rust 2015

1.0.7 May 14, 2020
1.0.6 Nov 9, 2017
1.0.5 Sep 19, 2016
1.0.4 Aug 30, 2016
1.0.0 Apr 6, 2015

#16 in Algorithms

Download history 1962663/week @ 2024-07-30 1974887/week @ 2024-08-06 1934441/week @ 2024-08-13 1995994/week @ 2024-08-20 1917731/week @ 2024-08-27 2065485/week @ 2024-09-03 1995528/week @ 2024-09-10 2036335/week @ 2024-09-17 2167914/week @ 2024-09-24 2500387/week @ 2024-10-01 2713488/week @ 2024-10-08 2666531/week @ 2024-10-15 2234470/week @ 2024-10-22 2098806/week @ 2024-10-29 2080183/week @ 2024-11-05 1814704/week @ 2024-11-12

8,678,945 downloads per month
Used in 33,710 crates (654 directly)

Apache-2.0 / MIT

23KB
311 lines

rust-fnv

An implementation of the Fowler–Noll–Vo hash function.

Read the documentation

About

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.

Usage

To include this crate in your program, add the following to your Cargo.toml:

[dependencies]
fnv = "1.0.3"

Using FNV in a HashMap

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.

Using FNV in a HashSet

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);

No runtime deps

Features