rust-lang/rust

Improve std::hash::Hasher to finish with an associated type

afranchuk opened this issue · 4 comments

std::hash::Hasher currently defines a finish() method that returns a fixed type (u64). This trait could be improved by changing the return type to some associated Output type. I don't see a particular reason this wouldn't work, since, for instance, std::collections::HashMap can simply provide a Hasher which produces the type it expects. This would be nice as then types implementing std::hash::Hash could be used with, for example, cryptographic hash functions. I am aware of the digest crate intended for that use case, but I don't see a reason not to improve the existing trait.

Hasher is a stable trait so this change cannot be made backwards compatibly, so we cannot make it at this point. As such, closing.

In theory an extension that provides a default could work here, but I imagine that it would run into lots of issues really quickly (e.g., inference, in particular for Hash trait impls, would be problematic).

I just want to remark that if RFC 2532 (associated type defaults) gets in then this change could be made in a backwards compatible way.

I don't think that's entirely true (or, at least, not in general) - Hash::hash takes a Hasher generically, and that can't change to also take a type param which would mean that the extension to this trait is largely useless.

Good point, you'd have to move the finish() method from Hasher to a separate trait. The only thing Hash should care about is the write methods of Hasher, I think? So yeah, a breaking change...