Conceptcore
Hash codes
Also called hash code, hash value, hashing, hashCode, GetHashCode, __hash__, hash function for keys, hash flooding, HashDoS, seeded hash.
A hash code is a number computed from a key that picks its bucket in a hash table. Equal keys must hash equal, keys must not change, and hashes on input need random seeds.
- Applies to
- core-languages
Idea
A hash table finds a key in about one step because it does not search: it computes a number from the key, the hash code, and uses that number to pick a bucket. Each language gives its types a hash function, such as __hash__ in Python, hashCode in Java or the Hash trait in Rust, and a program that uses its own types as keys must supply one or derive it. Three rules decide if the table works. Keys that are equal must have equal hash codes. A key must not change while it is in a table. The hash must spread keys over the buckets, also for keys that an attacker chooses. Value equality and identity states the basic rule; this page covers the practice.
from itertools import permutations
class Table: # a hash table with separate chaining
def __init__(self, hash_fn, eq, size=64):
self.hash, self.eq, self.compares = hash_fn, eq, 0
self.buckets = [[] for _ in range(size)]
def _bucket(self, key):
return self.buckets[self.hash(key) % len(self.buckets)]
def put(self, key, value):
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
self.compares += 1
if self.eq(k, key):
bucket[i] = (key, value)
return
bucket.append((key, value))
def get(self, key):
for k, v in self._bucket(key):
self.compares += 1
if self.eq(k, key):
return v
return None
def fnv1a(s): # FNV-1a, 32 bits: a simple hash with good spread
h = 2166136261
for byte in s.encode():
h = ((h ^ byte) * 16777619) % 2**32
return h
same_name = lambda a, b: a.lower() == b.lower() # case-insensitive equality
broken = Table(fnv1a, same_name) # hashes the raw text: breaks the contract
fixed = Table(lambda s: fnv1a(s.lower()), same_name)
for t in (broken, fixed):
t.put("Alan", 1912)
print("broken get('ALAN'):", broken.get("ALAN"), " fixed get('ALAN'):", fixed.get("ALAN"))
key = ["x", "y"] # a mutable key, hashed by its contents
t = Table(lambda k: fnv1a("".join(k)), lambda a, b: a == b)
t.put(key, "point")
key.append("z")
print("after the key changed:", t.get(key), t.get(["x", "y"]))
keys = ["".join(p) for p in permutations("abcdefg")][:500]
weak = Table(lambda s: sum(map(ord, s)), str.__eq__) # anagrams collide
strong = Table(fnv1a, str.__eq__)
for t in (weak, strong):
for k in keys:
t.put(k, True)
print(f"500 anagram keys: weak hash {weak.compares} compares, FNV-1a {strong.compares}")
broken get('ALAN'): None fixed get('ALAN'): 1912
after the key changed: None None
500 anagram keys: weak hash 124750 compares, FNV-1a 3910
The table keeps a list of entries in each bucket and counts the comparisons of keys. The first table treats names as equal without regard to case but hashes the raw text, so "ALAN" goes to a different bucket from "Alan" and the lookup fails; hashing the lower-case text fixes it. The second part changes a list after it became a key, and then neither the changed list nor a copy of the old one finds the entry. The last part puts 500 anagrams into two tables. A hash that adds the character codes gives all of them one code, so every insert compares against every earlier key, 124750 comparisons in total; FNV-1a spreads them and needs 3910.
How it works
The contract. Every language states the same rule. Python: "The only required property is that objects which compare equal have the same hash value".1 Java: "If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result."2 Rust writes it as k1 == k2 -> hash(k1) == hash(k2), "if two keys are equal, their hashes must also be equal", and adds: "Violating this property is a logic error."3 The reverse is not required: unequal keys can have one hash code, and the table then compares the keys. So a hash function must use only data that equality uses. A case-insensitive equality needs a case-insensitive hash, and an Account that is equal by id must hash only the id.
Deriving hashes. Writing the two functions by hand lets them drift apart when a field is added, so languages generate both from one list of fields. Python's frozen dataclasses, Java and C# records, Rust's #[derive(PartialEq, Eq, Hash)] and Kotlin's data classes do this. Go hashes every comparable struct by all its fields and does not let a program change that. C++ needs a specialization of std::hash or a hash object passed to the container, and C needs a function written by hand.
Combining fields. A hash of several fields must mix them, so that a change in any field changes the result, and so that (1, 2) and (2, 1) differ. Adding or XOR-ing the field hashes fails both tests, as the anagrams in the example show. The usual forms multiply the running value by an odd number before each field, as Java's Objects.hash and the formula of String.hashCode do, or call a mixing function such as HashCode.Combine in C# or the hash_combine idiom of Boost. Java fixes the string formula in its specification: "The hash code for a String object is computed as s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] using int arithmetic".4
Keys must not change. A table stores an entry in the bucket for its hash at the time of the insert. If the key changes later, the entry stays in the old bucket, and lookups by the new value or by an equal copy of the old value both fail, as the Java wrong block shows. Rust states it: "It is also a logic error for a key to be modified in such a way that the key’s hash, as determined by the Hash trait, or its equality, as determined by the Eq trait, changes while it is in the map."5 Python refuses to hash its mutable built-in types, and Go refuses slices, maps and functions as keys at compile time. Java and C# allow mutable keys and leave the rule to the programmer.
Hash flooding. If an attacker can predict the hash function, the attacker can send many keys with one hash code, and each insert then compares against all earlier keys, so n keys cost about n squared steps. In 2011 an advisory reported that "A variety of programming languages suffer from a denial-of-service (DoS) condition against storage functions of key/value pairs in hash data structures, the condition can be leveraged by exploiting predictable collisions in the underlying hashing algorithms."6 A web form with a few megabytes of such keys could keep a server busy for minutes. Java's String.hashCode makes such keys easy to build: "Aa" and "BB" collide, so every string made of these two parts collides with every other of the same length.
Random seeds. The defense is a hash function with a secret key chosen when the program starts, so that an attacker cannot predict collisions. Python salts the hashes of str and bytes: "Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python."1 PEP 456 then made SipHash the default, because "The current hash algorithm and its randomization is not resilient against attacks."7 Rust's HashMap uses an "algorithm selected to provide resistance against HashDoS attacks", and "The algorithm is randomly seeded".5 Go seeds each map, and its hash/maphash package gives the same seeded hashes to programs: "Two Hash objects with different seeds will very likely behave differently."8 .NET randomizes string hashes and the seed of HashCode for each process.
Hashes are not stable. With random seeds, the hash of a value changes from one run to the next. The C++ standard allows this: "Hash functions are only required to produce the same result for the same input within a single execution of a program; this allows salted hashes that prevent collision denial-of-service attacks."9 The .NET documentation states the rules for programs: "Do not serialize hash code values or store them in databases." and "Do not send hash codes across application domains or processes."10 A file name, a cache key or a shard number that must stay the same across runs needs a fixed hash function, such as FNV-1a or a cryptographic hash, not the built-in hash code.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Idiom | |
| TypeScript | Idiom | TypeScript uses the Map and Set of JavaScript, which compare objects by identity, so keys are built as strings, but no example file exists. |
| Go | Native | |
| Rust | Standard library | |
| Kotlin | Native | Data classes generate equals and hashCode from the properties of the primary constructor, on the JVM model, but no example file exists because kotlinc is not installed. |
| SQL | Does not apply | The database engine uses hashing inside hash joins and hash indexes, and queries do not define hash functions. |
| Bash | Native | Declare -A makes an associative array with string keys that the shell hashes, but no example file exists. |
| PowerShell | Native | The hashtable literal makes a hash table that uses the GetHashCode and Equals methods of .NET, case-insensitive for string keys by default, but no example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no hash tables. |
| CSS | Does not apply | CSS has no hash tables. |
| Regular expressions | Does not apply | Regular expressions have no hash tables. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | __hash__, hash(), frozen dataclasses; salted str hashes |
| JavaScript | idiom | Map and Set by SameValueZero; string keys built by hand |
| TypeScript | idiom | as JavaScript |
| Java | native | hashCode and equals, records, Objects.hash |
| Kotlin | native | hashCode, data classes |
| C# | native | GetHashCode, records, IEqualityComparer<T>, HashCode |
| Go | native | comparable keys hashed by the runtime; hash/maphash |
| Rust | stdlib | the Hash trait, #[derive(Hash)], RandomState |
| C | idiom | hash functions and tables written by hand |
| C++ | stdlib | std::hash specializations, unordered containers |
| Bash | native | declare -A with string keys |
| PowerShell | native | hashtables on .NET hashing |
| SQL | n/a | hash joins and indexes inside the engine |
| Regex | n/a | no hash tables |
| HTML | n/a | no hash tables |
| CSS | n/a | no hash tables |
Python, Java, Kotlin, C# and Go hash keys in the language or in its core object model, so they are native. Rust and C++ put the hash trait or template and the tables in the standard library. JavaScript has hash tables but no way to define equality or a hash for a type, so the idiom builds a string key from the fields. C has neither tables nor hash functions in its standard library.
The example files show the three rules. Java and C# show derived hashes in records, a hash written by hand on one field, and C# comparers that change equality and the hash together. The Java wrong block changes a key in a set, and the Go and Rust fails blocks show compilers that reject keys that cannot be hashed. Python and Rust show random seeds, Java shows the colliding strings of a fixed formula, and C++ shows that std::hash<const char*> hashes the address and not the text. The C file writes FNV-1a and a table with open addressing.
import os
import subprocess
import sys
from dataclasses import dataclass
@dataclass(frozen=True) # frozen: __eq__ and __hash__ from the same fields
class Point:
x: int
y: int
seen = {Point(1, 2): "a"}
print(Point(1, 2) in seen, hash(Point(1, 2)) == hash((1, 2)))
print("1, 1.0 and True:", hash(1) == hash(1.0) == hash(True), len({1, 1.0, True}))
print("hash(-1) == hash(-2):", hash(-1) == hash(-2))
try:
{[1, 2]: "list"}
except TypeError:
print("TypeError: a list cannot be a key, because it is mutable")
def str_hash(seed): # the hash of a str depends on a per-process seed
env = dict(os.environ, PYTHONHASHSEED=str(seed))
code = "print(hash('hello'))"
return subprocess.run([sys.executable, "-c", code], env=env,
capture_output=True, text=True).stdout
print("same seed, same hash:", str_hash(1) == str_hash(1))
print("other seed, same hash:", str_hash(1) == str_hash(2))
True True
1, 1.0 and True: True 1
hash(-1) == hash(-2): True
TypeError: a list cannot be a key, because it is mutable
same seed, same hash: True
other seed, same hash: False
- Verdict: native.
hash()and__hash__are part of the language, anddictandsetare built in. A frozen dataclass makes__eq__and__hash__from the same fields, and its hash equals the hash of the tuple of the fields. Numbers that compare equal hash equal, so1,1.0andTrueare one key. A list has no hash, because it can change. The hash of astris salted with a random value for each process; the example starts two interpreters with fixedPYTHONHASHSEEDvalues to show that a different seed gives a different hash.
#include <cstddef>
#include <functional>
#include <iostream>
#include <string>
#include <string_view>
#include <unordered_map>
struct Point {
int x, y;
bool operator==(const Point&) const = default;
};
// The boost::hash_combine idiom: mix each field into the seed
inline void hash_combine(std::size_t& seed, std::size_t h) {
seed ^= h + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2);
}
template <>
struct std::hash<Point> {
std::size_t operator()(const Point& p) const noexcept {
std::size_t seed = 0;
hash_combine(seed, std::hash<int>{}(p.x));
hash_combine(seed, std::hash<int>{}(p.y));
return seed;
}
};
int main() {
std::unordered_map<Point, std::string> points{{{1, 2}, "a"}};
std::cout << "struct key: " << points.at({1, 2}) << "\n";
std::cout << "swapped fields differ: " << std::boolalpha
<< (std::hash<Point>{}({1, 2}) != std::hash<Point>{}({2, 1})) << "\n";
char buf[] = "ada";
const char* lit = "ada";
std::cout << "hash<const char*> equal: "
<< (std::hash<const char*>{}(buf) == std::hash<const char*>{}(lit)) << "\n";
std::cout << "hash<string_view> equal: "
<< (std::hash<std::string_view>{}(buf) == std::hash<std::string_view>{}(lit)) << "\n";
}
struct key: a
swapped fields differ: true
hash<const char*> equal: false
hash<string_view> equal: true
This code does not compile, on purpose.
#include <unordered_set>
struct Point {
int x, y;
bool operator==(const Point&) const = default;
};
int main() {
std::unordered_set<Point> seen;
seen.insert({1, 2});
return static_cast<int>(seen.size());
}
- Verdict: stdlib.
std::hashand the unordered containers are in the standard library. A type gets a hash from a specialization ofstd::hash, and the hash_combine idiom from Boost mixes the hashes of the fields.std::hash<const char*>hashes the pointer, not the characters, so two equal strings at different addresses hash differently; hash astd::string_viewinstead. The fails block puts a type with nostd::hashinto anunordered_set, and the compiler rejects it.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Objects;
public class Main {
record Point(int x, int y) {} // equals and hashCode come from the fields
static final class Account { // written by hand: both methods use the same field
final String id;
final int visits;
Account(String id, int visits) { this.id = id; this.visits = visits; }
@Override public boolean equals(Object o) {
return o instanceof Account a && a.id.equals(id);
}
@Override public int hashCode() { return Objects.hash(id); }
}
public static void main(String[] args) {
var points = new HashMap<Point, String>();
points.put(new Point(1, 2), "a");
System.out.println("record key: " + points.get(new Point(1, 2)));
var accounts = new HashSet<Account>();
accounts.add(new Account("ada", 1));
System.out.println("same id: " + accounts.contains(new Account("ada", 7)));
// String.hashCode is s[0]*31^(n-1) + ... + s[n-1], the same in every run
System.out.println("\"Aa\" " + "Aa".hashCode() + ", \"BB\" " + "BB".hashCode());
System.out.println("\"AaAa\" " + "AaAa".hashCode() + ", \"BBBB\" " + "BBBB".hashCode()
+ ", \"AaBB\" " + "AaBB".hashCode());
}
}
record key: a
same id: true
"Aa" 2112, "BB" 2112
"AaAa" 2031744, "BBBB" 2031744, "AaBB" 2031744
This code runs but gives a wrong answer on purpose.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> path = new ArrayList<>(List.of("home", "ada"));
var visited = new HashSet<List<String>>();
visited.add(path);
path.add("docs"); // the key changes while it is in the set
System.out.println("contains path: " + visited.contains(path));
System.out.println("contains a copy: " + visited.contains(List.of("home", "ada", "docs")));
System.out.println("size " + visited.size() + ", iterator finds it: "
+ visited.iterator().next().equals(path));
}
}
contains path: false
contains a copy: false
size 1, iterator finds it: true
- Verdict: native. Every object has
equalsandhashCode, and records generate both from their components. A class written by hand must use the same fields in both, asAccountdoes withObjects.hash. The specification ofString.hashCodefixes the formula, so every run gives the same value, and strings that collide are easy to build:"Aa"and"BB"have one hash, so every string made of these two blocks does too. Since Java 8,HashMapturns a long chain into a balanced tree, which limits the damage. - The wrong block changes a list after it is added to a
HashSet. The set keeps the entry in the bucket of the old hash, socontainsfails for the list itself and for an equal copy, while iteration still finds it.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* FNV-1a, 64 bits: fold each byte into the hash with xor, then multiply */
static uint64_t fnv1a(const void *data, size_t n, uint64_t h) {
const unsigned char *p = data;
for (size_t i = 0; i < n; i++)
h = (h ^ p[i]) * 1099511628211u;
return h;
}
#define FNV_START 14695981039346656037u
struct point { int32_t x, y; };
/* Hash the fields, not the bytes of the struct, so padding never counts */
static uint64_t point_hash(struct point p) {
uint64_t h = fnv1a(&p.x, sizeof p.x, FNV_START);
return fnv1a(&p.y, sizeof p.y, h);
}
/* A set of strings with open addressing and linear probing */
#define CAP 8
static const char *slots[CAP];
static int insert(const char *s) {
size_t i = fnv1a(s, strlen(s), FNV_START) % CAP, probes = 1;
while (slots[i] && strcmp(slots[i], s) != 0) {
i = (i + 1) % CAP;
probes++;
}
slots[i] = s;
return (int)probes;
}
int main(void) {
const char *words[] = {"ada", "alan", "grace", "linus", "ada", "barbara"};
for (size_t i = 0; i < sizeof words / sizeof *words; i++)
printf("%s: %d probe(s)\n", words[i], insert(words[i]));
struct point a = {1, 2}, b = {1, 2}, c = {2, 1};
printf("point hashes equal: %d, swapped fields equal: %d\n",
point_hash(a) == point_hash(b), point_hash(a) == point_hash(c));
printf("fnv1a(\"\") = %llu\n", (unsigned long long)fnv1a("", 0, FNV_START));
return 0;
}
ada: 1 probe(s)
alan: 1 probe(s)
grace: 2 probe(s)
linus: 2 probe(s)
ada: 1 probe(s)
barbara: 1 probe(s)
point hashes equal: 1, swapped fields equal: 0
fnv1a("") = 14695981039346656037
- Verdict: idiom. The C standard library has no hash table and no hash function; POSIX
hsearchhas one global table. Programs write their own, and FNV-1a, shown here, is a common simple choice for short keys. The set uses open addressing: a key that finds its slot taken tries the next slot. The point hash mixes the fields one at a time, so the bytes of padding never enter the hash, and swapping the fields changes the result.
using System;
using System.Collections.Generic;
using System.Linq;
var points = new Dictionary<Point, string> { [new Point(1, 2)] = "a" };
Console.WriteLine($"record key: {points[new Point(1, 2)]}");
var ages = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) { ["Alan"] = 1912 };
Console.WriteLine($"ALAN with an ignore-case comparer: {ages["ALAN"]}");
var arrays = new HashSet<int[]> { new[] { 1, 2 } };
var byContents = new HashSet<int[]>(new SequenceComparer()) { new[] { 1, 2 } };
Console.WriteLine($"array by reference: {arrays.Contains(new[] { 1, 2 })}, by contents: {byContents.Contains(new[] { 1, 2 })}");
var a = new Account("ada", 1);
var b = new Account("ada", 7);
Console.WriteLine($"same id: {a.Equals(b)}, same hash: {a.GetHashCode() == b.GetHashCode()}");
readonly record struct Point(int X, int Y);
sealed class Account(string id, int visits)
{
public string Id { get; } = id;
public int Visits { get; } = visits;
public override bool Equals(object? o) => o is Account a && a.Id == Id;
public override int GetHashCode() => HashCode.Combine(Id); // seeded per process
}
sealed class SequenceComparer : IEqualityComparer<int[]>
{
public bool Equals(int[]? x, int[]? y) => x is not null && y is not null && x.SequenceEqual(y);
public int GetHashCode(int[] xs)
{
var h = new HashCode();
foreach (var x in xs) h.Add(x);
return h.ToHashCode();
}
}
record key: a
ALAN with an ignore-case comparer: 1912
array by reference: False, by contents: True
same id: True, same hash: True
- Verdict: native. Every object has
EqualsandGetHashCode, and records generate both. AnIEqualityComparer<T>gives a collection its own equality and hash, such asStringComparer.OrdinalIgnoreCase, or comparison of arrays by contents in place of by reference.HashCode.CombineandHashCode.Addmix fields with a seed that is random for each process, and string hashes are randomized in the same way, so a hash code must not be stored or sent to another process.
// Map and Set compare object keys by identity, not by contents
const byObject = new Map([[{ x: 1, y: 2 }, "a"]]);
console.log("object key:", byObject.get({ x: 1, y: 2 }));
// The idiom: derive a string key from the fields that define equality
const key = (p) => `${p.x},${p.y}`;
const byKey = new Map([[key({ x: 1, y: 2 }), "a"]]);
console.log("string key:", byKey.get(key({ x: 1, y: 2 })));
// SameValueZero: NaN finds NaN, and -0 is the same key as +0
const m = new Map([[NaN, "nan"], [0, "zero"]]);
console.log(m.get(NaN), m.get(-0), new Set([1, "1", 1.0]).size);
// A plain object turns every key into a string
const counts = {};
for (const k of [1, "1", true, "true"]) counts[k] = (counts[k] ?? 0) + 1;
console.log(counts);
object key: undefined
string key: a
nan zero 2
{ '1': 2, true: 2 }
- Verdict: idiom.
MapandSethash their keys inside the engine, but a program cannot define equality or a hash for its own types: objects are equal only to themselves, under the SameValueZero rule. The idiom derives a primitive key, usually a string, from the fields that define equality. A plain object converts every key to a string, so1and"1"are one key.
package main
import (
"fmt"
"hash/maphash"
"math"
)
type Point struct{ X, Y int } // comparable: a struct of comparable fields
func main() {
points := map[Point]string{{1, 2}: "a"}
fmt.Println("struct key:", points[Point{1, 2}])
// A slice cannot be a key; an array of fixed length can.
paths := map[[2]string]bool{{"home", "ada"}: true}
fmt.Println("array key:", paths[[2]string{"home", "ada"}])
// NaN is not equal to itself, so each NaN key is a new entry
m := map[float64]int{}
m[math.NaN()] = 1
m[math.NaN()] = 2
_, found := m[math.NaN()]
fmt.Println("NaN keys:", len(m), "found:", found)
// maphash: the same seed gives the same hash; seeds are random per call
s1, s2 := maphash.MakeSeed(), maphash.MakeSeed()
fmt.Println("same seed:", maphash.String(s1, "hello") == maphash.String(s1, "hello"))
fmt.Println("two seeds:", maphash.String(s1, "hello") == maphash.String(s2, "hello"))
fmt.Println("comparable:", maphash.Comparable(s1, Point{1, 2}) == maphash.Comparable(s1, Point{1, 2}))
}
struct key: a
array key: true
NaN keys: 2 found: false
same seed: true
two seeds: false
comparable: true
This code does not compile, on purpose.
package main
import "fmt"
func main() {
seen := map[[]string]bool{}
seen[[]string{"home", "ada"}] = true
fmt.Println(len(seen))
}
- Verdict: native. Maps are built in, and the runtime hashes any comparable key with a random seed for each map: numbers, strings, pointers, arrays and structs of comparable fields. A program cannot give a type its own hash or equality. The fails block uses a slice as a key, and the compiler rejects it because slices are not comparable; an array or a string built from the slice works. A NaN key is never equal to itself, so each insert adds an entry that no lookup finds.
hash/maphashgives seeded hashes for programs that build their own tables.
use std::collections::hash_map::RandomState;
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash, Hasher};
#[derive(Debug, PartialEq, Eq, Hash)] // derived together, so they agree
struct Point {
x: i32,
y: i32,
}
struct Account {
id: String,
visits: u32, // not part of equality, so not part of the hash
}
impl PartialEq for Account {
fn eq(&self, other: &Self) -> bool { self.id == other.id }
}
impl Eq for Account {}
impl Hash for Account {
fn hash<H: Hasher>(&self, state: &mut H) { self.id.hash(state) }
}
fn main() {
let mut points = HashMap::new();
points.insert(Point { x: 1, y: 2 }, "a");
println!("struct key: {:?}", points.get(&Point { x: 1, y: 2 }));
let mut ages: HashMap<String, u32> = HashMap::new();
ages.insert("Alan".to_string(), 1912);
println!("lookup by &str: {:?}", ages.get("Alan")); // String: Borrow<str>
let (a, b) = (Account { id: "ada".into(), visits: 1 }, Account { id: "ada".into(), visits: 7 });
let s = RandomState::new();
println!("same id: {}, same hash: {}, visits {} and {}", a == b, s.hash_one(&a) == s.hash_one(&b), a.visits, b.visits);
// Each RandomState has its own random keys for SipHash
let (s1, s2) = (RandomState::new(), RandomState::new());
println!("same state: {}, two states: {}", s1.hash_one("hello") == s1.hash_one("hello"), s1.hash_one("hello") == s2.hash_one("hello"));
}
struct key: Some("a")
lookup by &str: Some(1912)
same id: true, same hash: true, visits 1 and 7
same state: true, two states: false
This code does not compile, on purpose. The error is E0277.
use std::collections::HashSet;
#[derive(PartialEq, Eq)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let mut seen = HashSet::new();
seen.insert(Point { x: 1, y: 2 });
println!("{}", seen.len());
}
- Verdict: stdlib. The
Hashtrait andHashMapare in the standard library, and#[derive(PartialEq, Eq, Hash)]makes equality and hash agree. A manual implementation, such asAccount, must hash only the fields thateqcompares.HashMapuses SipHash 1-3 with random keys fromRandomState, so two states hash the same string differently. TheBorrowtrait lets a map withStringkeys look up a&str. The fails block uses a type withoutHashas a key, and the compiler reports E0277.
Variations and related ideas
- Separate chaining and open addressing. A table either keeps a list in each bucket, as the idea block does, or stores keys in the array and probes the next slots, as the C file does. Swiss tables, used by Abseil, Rust and recent versions of Go, probe groups of slots with SIMD instructions.
- Tree bins. Since Java 8,
HashMapturns a long chain into a balanced tree when the keys are comparable, so many collisions cost log n steps, not n. - Perfect hashing. For a fixed set of keys, such as the keywords of a language, a generator such as gperf builds a hash function with no collisions.
- Consistent hashing. Distributed caches assign keys to servers so that adding a server moves few keys.
- Cryptographic hashes. SHA-256 and BLAKE3 resist collisions even when every input is chosen by an attacker, and they are stable across runs, but they are slower than table hashes. See generate random numbers for the related use of hashes as random sources.
- Identity hashes. Objects with no equality of their own hash by identity, as Java's
System.identityHashCodeand Python's default__hash__do. - Uses. Hash tables underlie removing duplicates, counting words, caches, sets and joins.
Pitfalls
- Equality and hash that disagree. Overriding
equalsor__eq__without the hash, or hashing a field that equality ignores, makes equal keys miss each other. Derive both from one list of fields. - Mutable keys. Changing a field that the hash uses, while the object is a key, loses the entry. Use immutable types as keys; see immutability.
- Floating-point keys. NaN is not equal to itself, so each NaN key in a Go map is a new entry that no lookup finds. In Python
0.0and-0.0are one key, but Java'sDouble.equalstreats them as two keys, and values that differ in the last bit are always different keys. See floating-point arithmetic. - Keys of mixed types. In Python,
1,1.0andTrueare one key; in a JavaScript object,1and"1"are one key. - Hashing pointers.
std::hash<const char*>and the default hash of most objects use the address, so two equal strings at different places differ. - Stored hash codes. A built-in hash saved to a file or a database, or sent to another process, will not match the next run. Use a fixed, documented function.
- Predictable hashes on input. A table filled from requests, JSON objects or headers with a fixed hash invites flooding. Keep the seeded default, and limit the number of keys per request.
- Weak combining. Summing or XOR-ing the hashes of fields makes all permutations collide, and XOR makes
(x, x)hash to zero.
Cost
A good hash makes a lookup cost one hash computation and about one comparison. The hash itself reads the whole key, so a long string costs time in proportion to its length; Java caches the hash in each String for this reason. With a bad or attacked hash every key lands in one bucket and each lookup costs n comparisons, or log n with Java's tree bins. Seeded hashes such as SipHash are a few times slower than FNV or a multiply and shift for short keys, which is why Rust lets a program choose a faster hasher when its keys are not from untrusted input.
History
Hans Peter Luhn of IBM described hashing in an internal memo in 1953, and Arnold Dumey published the idea in 1956. Glenn Fowler, Landon Curt Noll and Phong Vo designed the FNV hash in 1991. Scott Crosby and Dan Wallach showed in 2003 that predictable hashes let an attacker slow a program down, and Perl randomized its hashes in the same year. In December 2011, a talk at the 28C3 conference and an advisory showed the attack on PHP, Java, Python, Ruby and others,6 and Java 8 later added tree bins to HashMap.
Jean-Philippe Aumasson and Daniel J. Bernstein published SipHash, a fast keyed hash for short inputs, in 2012. Python 3.3 turned on hash randomization by default in the same year, and Python 3.4 made SipHash its string hash through PEP 456, which "proposes SipHash as default string and bytes hash algorithm to properly fix hash randomization once and for all".7 Rust used SipHash from its first release and moved to SipHash 1-3,5 .NET Core randomized string hashes, and Go added hash/maphash in 1.14.8
References
- Data model, The Python Language Reference, object.__hash__
- Class Object, Java SE 25 API documentation, hashCode()
- Trait Hash, Rust standard library documentation, Hash and Eq
- Class String, Java SE 25 API documentation, hashCode()
- Struct HashMap, Rust standard library documentation, Description
- oCERT-2011-003, multiple implementations denial-of-service via hash algorithm collision, Description
- PEP 456, Secure and interchangeable hash algorithm, Abstract and Rationale
- Package maphash, Go standard library documentation, Overview and type Seed
- std::hash, cppreference.com, Notes
- Object.GetHashCode Method, .NET API documentation, Remarks
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 81CRZ8 Edit this page History Report an error Markdown