skip to content

A Rust Username type has a case-insensitive hand-written PartialEq but derives Hash; why does a HashSet<Username> accept both "Alice" and "alice", and how do you fix it?

level: seniorimportance: should knowfreq 35%

answer

  1. equal keys, different buckets
  2. one direction of implication
  3. a logic error, not UB
  4. hash what eq compares

basics

~20 s

Hash must agree with Eq: k1 == k2 implies hash(k1) == hash(k2). The derived Hash feeds the exact bytes, so equal usernames usually hash apart and the set never compares them. Hash the normalised form eq compares.

solid answer

~40 s

`Hash`'s documented contract is `k1 == k2 -> hash(k1) == hash(k2)`, and `HashSet` relies on it: the hash picks where to look, and `eq` is only consulted for entries found there. The derived `Hash` on `Username(String)` hashes the exact bytes, while the hand-written `eq` uses `eq_ignore_ascii_case`, so "Alice" and "alice" are equal but almost always hash differently; the second `insert` returns `true` and `contains` misses. std calls this a logic error: results are unspecified, but the map must not cause undefined behaviour. rustc accepts the code; clippy's `derived_hash_with_manual_eq` is deny-by-default. Fix it by implementing `Hash` over the same normalised bytes, ASCII-lowercased plus a terminator, or by normalising once in the constructor and deriving all three traits.

code

rust · 23 lines
rust
use std::collections::HashSet;

// Usernames compare case-insensitively...
#[derive(Debug, Hash)] // ...but the derived Hash hashes the exact bytes.
struct Username(String);

impl PartialEq for Username {
    fn eq(&self, other: &Self) -> bool {
        self.0.eq_ignore_ascii_case(&other.0)
    }
}
impl Eq for Username {}

fn main() {
    let a = Username("Alice".to_string());
    let b = Username("alice".to_string());
    println!("a == b: {}", a == b);
    let mut taken = HashSet::new();
    taken.insert(a);
    println!("inserted again: {}", taken.insert(b));
    println!("len: {}", taken.len());
    println!("contains ALICE: {}", taken.contains(&Username("ALICE".to_string())));
}

go deeper

for a junior

Recall that equal values must produce equal hashes, and that deriving PartialEq, Eq and Hash together guarantees it.

for a middle

Explain why a set looks only where the hash points, so a mismatched Hash hides an equal key, and show a matching manual Hash.

for a senior

Diagnose duplicate entries as a Hash and Eq mismatch, cite the logic-error clause, rely on clippy's deny lint, and prefer normalising in the constructor.

for a principal

Make normalised newtypes the team pattern for identifiers compared loosely, so equality, hashing and ordering cannot drift apart.

## The contract between Hash and Eq The `Hash` trait's documentation states one property that must hold whenever a type implements both `Hash` and `Eq`: ```plaintext k1 == k2 -> hash(k1) == hash(k2) ``` If two keys are equal, their hashes must be equal. The implication runs one way only: unequal keys may share a hash (a collision), and that is merely slower. The docs add that you get this for free when you derive both with `#[derive(PartialEq, Eq, Hash)]`, because the generated code feeds exactly the fields that the generated `eq` compares. Violating the property is called a **logic error**. In std's wording the resulting behaviour is not specified, but it must not become undefined behaviour, and `unsafe` code must not rely on these impls being correct. `HashMap`'s own docs spell out what "not specified" can mean: panics, incorrect results, aborts, memory leaks and non-termination, confined to the map that saw the error. ## Why the set accepts a duplicate A hash set uses the hash to decide where an entry lives and compares with `eq` only against entries it finds there: 1. `insert(Username("Alice"))` hashes the bytes `A l i c e` and stores the entry. 2. `insert(Username("alice"))` hashes `a l i c e`, a different byte sequence, so it almost certainly looks in a different place. 3. Finding no candidate there, the set never calls `eq` and concludes the key is new. `insert` returns `true` and `len()` becomes 2. 4. `contains(&Username("ALICE"))` hashes a third byte sequence and almost certainly returns `false`, although `eq` says it equals both stored entries. The outcome is unspecified rather than guaranteed: by chance the two hashes could select the same slot, and then `eq` would catch the duplicate. That inconsistency is the real damage, because a uniqueness check that works on one run and fails on another is worse than one that always fails. For a username registry the result is two accounts that the rest of the system considers the same person. ## What the tools tell you - **rustc** compiles this without a word. `Hash` and `PartialEq` are separate traits and the compiler does not relate them. - **clippy** catches the most common form. `clippy::derived_hash_with_manual_eq` reports "you are deriving `Hash` but have implemented `PartialEq` explicitly", and it is **deny-by-default**, so `cargo clippy` fails. Teams that run clippy in CI see this before it ships. - **Tests** catch it only if they check consistency: assert that two values you consider equal produce the same hash. The `Hash` docs recommend exactly that, rather than pinning hard-coded hash values, which are not stable across platforms or compiler versions. ## Two correct fixes 1. **Hash what `eq` compares.** Implement `Hash` by hand over the same normalisation: ```rust impl Hash for Username { fn hash<H: Hasher>(&self, state: &mut H) { for b in self.0.bytes() { state.write_u8(b.to_ascii_lowercase()); } state.write_u8(0xff); } } ``` The trailing `0xff` mirrors the default `Hasher::write_str`, which `str`'s own `Hash` calls: it keeps the fed data **prefix-free**, so a type hashing several strings in a row does not make `("ab", "c")` and `("a", "bc")` feed identical bytes. 2. **Normalise once, then derive.** Store the canonical form, for instance lowercase it in `Username::new`, keep the field private, and derive `PartialEq, Eq, Hash` together. Equality and hashing then agree by construction, and so does a derived `Ord` if you add one. Keep the original spelling in a second field if you need to display it, and leave that field out of all three impls. ## Edge cases worth knowing - **Hashing fewer fields than `eq` compares is consistent.** If `eq` compares `id` and `name` but `hash` feeds only `id`, equal values still hash alike; you only get more collisions. Hashing **more** than `eq` compares is the broken direction, which is the derived-Hash-with-narrow-eq mistake above. - **ASCII is not Unicode.** `eq_ignore_ascii_case` folds only A–Z. If `eq` uses a Unicode-aware normalisation, `hash` must use the identical one; mixing `to_lowercase` in one and ASCII folding in the other reintroduces the bug for non-ASCII names. - **Ordering must agree too.** If the type also implements `Ord`, `cmp` must return `Equal` exactly when `eq` is true; a derived `Ord` beside this hand-written `eq` would compare raw bytes and disagree. - **Mutating a key in place** (through a `Cell` or `RefCell` inside it) after insertion is a separate logic error the collection docs describe, with the same unspecified consequences.

  • Is it acceptable for Hash to use fewer fields than PartialEq compares?
    Yes. The contract only requires equal values to hash alike, and feeding a subset of the compared fields guarantees that. The cost is more collisions, since values differing only in the skipped fields share a hash. The broken direction is hashing a field that `eq` ignores.
  • Why does std say a broken Hash impl must not cause undefined behaviour, and who carries that burden?
    `Hash`, `Eq` and `Ord` are safe traits anyone can implement wrongly, so code using them must stay memory-safe regardless. The burden is on the consumer: `HashMap`'s internals are written so a logic error produces wrong answers, panics or leaks inside that map, never UB, and `unsafe` code must not rely on these impls being correct.

  • Equal hashes are required to imply equal keys.
  • rustc rejects a derived Hash beside a hand-written PartialEq.
  • A Hash that disagrees with Eq is undefined behaviour in Rust.
  • Hashing fewer fields than eq compares also breaks the contract.
  • Lowercasing with to_lowercase in hash matches eq_ignore_ascii_case for every input.
  • Pinning exact hash values in tests is the best consistency check.