Skip to content

lint Hash impls with matches on enums but no mem::discriminant call #4067

Open
@oli-obk

Description

@oli-obk

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.L-correctnessLint: Belongs in the correctness lint groupT-middleType: Probably requires verifiying types

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions