Skip to content

Spec request. Hasher: is write_u32 eqivalent to 4 calls of write_u8? #42951

Closed
@stepancheg

Description

@stepancheg

Currently Hasher::write_u32 is implemented as self.write(&unsafe { mem::transmute::<_, [u8; 4]>(i) }). The question is: is it a requirement for all Hasher implementations?

In other words, is is true, that for each hasher implementation, call

hasher.write_32(0x01020304);

must be equivalent to

hasher.write_8(0x04);
hasher.write_8(0x03);
hasher.write_8(0x02);
hasher.write_8(0x01);

?

(assuming host is little-endian).

Why is it important.

Suppose, you want to implement very simple hasher with state updated like state = state * 31 + update.

If Hasher does not have requirement as above, hasher can be implemented by simply casting any operand to u64 and avoiding dealing with unaligned/smaller than u64 integers:

impl Hasher for MyHasher {
    fn write_u8(&mut self, v: u8) {
        self.write_u64(v as u64);
    }

    fn write_u64(&mut self, v: u64) {
        self.state = (self.state * 31).wrapping_add(v);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.E-mediumCall for participation: Medium difficulty. Experience needed to fix: Intermediate.I-needs-decisionIssue: In need of a decision.P-mediumMedium priorityT-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