Skip to content

Derived Hash for repr(u8) enum submits 8 bytes to Hasher instead of 1 #39137

Closed
@kryptan

Description

@kryptan

Automatically derived Hash for an enum marked as repr(u8) will hash 8 bytes when it is only necessary to hash just one. When hashing large value containing many such enums this will lead to 8x slower hashing than necessary.

Example:

use std::hash::{Hash, Hasher};

struct H;

impl Hasher for H {
    fn finish(&self) -> u64 {
        unreachable!()
    }

    fn write(&mut self, bytes: &[u8]) {
        println!("{:?}", bytes);
    }
}

#[repr(u8)]
#[derive(Hash)]
enum E {
    A,
    B,
}

fn main() { 
    E::A.hash(&mut H);
}

prints [0, 0, 0, 0, 0, 0, 0, 0] while I expected it to print [0] just like 0u8.hash(&mut H).

This behavior is the same on recent stable, beta and nightly (1.14, 1.15, 1.16).


EDIT: Added second variant to the enum. Previous example with single variant doesn't print anything anymore because of #42709.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.I-slowIssue: Problems and improvements with respect to performance of generated code.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions