rust-lang / rust-lang/rust-clippy

lint `Hash` impls with `match`es on enums but no `mem::discriminant` call

Open
#4,067 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint E-medium L-correctness T-middle
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Implementing Hash by hashing just the fields of enum variants may cause hash collisions. E.g.

enum Foo {
    A(i32),
    B(i32),
}
impl Hash for Foo {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        match self {
             Foo::A(i) => i.hash(hasher),
             Foo::B(i) => i.hash(hasher),
        }
    }
}

would only hash the i32s, which makes the hash of Foo::A(42) equal to the hash of Foo::B(42). What's missing here is a call to mem::discriminant(self).hash(hasher); to differentiate between the variants.

This will lead to false positives if the user is doing some sort of manual scheme to differentiate between the variants, but in general the discriminant scheme should be preferred.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no source file or test. Start from the Rust enum Hash example and locate the relevant Clippy lint entry point and test conventions; done means detecting matches that hash variant fields without hashing mem::discriminant, while accounting for the noted false positives.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.