[swift-evolution] Pluggable hash algorithm for containers

Ray Fix rayfix at gmail.com
Fri Dec 4 12:45:45 CST 2015

> On Dec 3, 2015, at 8:29 PM, Dmitri Gribenko <gribozavr at gmail.com> wrote:
> A prototype is here (written before Howard's talk, so it probably uses
> different terms):
> https://github.com/apple/swift/blob/master/validation-test/stdlib/HashingPrototype.swift

Thank your for the excellent pointer, Dmitri.  I will look into that as I get setup to build, test, and make actual changes.

> However, I couldn't make it interoperate with NSObject.hash in both
> directions: you should be able to override 'var hash' and get an
> implementation of Hashable based on that, and vice versa.  It could be
> solvable with protocol extensions now, I haven't looked at that
> prototype for more than a year -- help and patches appreciated.

As you know, a hashing algorithm just needs to consume raw bytes.  The HasherType protocol could use protocol extensions to provide a clean API to standard types like Int and Float, Double, String, Bool, UInt32, Sequences, etc.  

extension CGPoint : NewHashable {
  func combineInto(hasher: Hasher) {

What would be even better is if there was some interspection with a default implementation so the user code could look like this:

extension CGPoint : NewHashable {}

but that is dependent on another language feature.

The default implementation of hash is to call combineInto(Hasher) with a legacy hasher and immediately squeeze.  Might even want this to be statically dispatched (an extension with no protocol definition).  

extension NewHashable {
    var hash: Int {
         var h = LegacyHasher()
         return h.squeezeHashValue()

Any thoughts?


More information about the swift-evolution mailing list