2

Apple's Hasher documentation tells that Hasher generates a different hash value on every execution and that hashes shouldn't persist across multiple executions.

Do not save or otherwise reuse hash values across executions of your program. Hasher is usually randomly seeded, which means it will return different values on every new execution of your program. The hash algorithm implemented by Hasher may itself change between any two versions of the standard library.

I do need, however, a way to generate a hash that is reproducible across multiple sessions. I am trying to use the hash value to differentiate between labels of a hashable structure. Since the input data may come from different executions, hashes wouldn't match if I used Hasher and Hashable.

I've considered writing an implementation of a murmur hashing algorithm, but those generally apply to string values, not optional structures.

Is there an alternative to Hasher in Swift that I could use to get reproducible hashes with arbitrary structures? Is there a hashing function that accepts a starting seed?

Thank you for your help!

maticzav
  • 880
  • 9
  • 17
  • 1
    Wouldn't your "hasher" be satisfied with a simple algorithm of concatenating the string representation of all properties? – New Dev Dec 09 '20 at 23:12
  • 1
    "I am trying to use the hash value to differentiate between labels of a hashable structure." This sounds like you also need your hashes to be collision resistant, which Hasher also doesn't promise. Note that Murmur is weakly collision resistant (it's probably fine as long as you don't have someone trying to create a collision). I'd probably recommend using SipHash with a static seed because there's already a good implementation in stdlib, though private (see https://github.com/apple/swift/blob/main/stdlib/public/core/SipHash.swift) – Rob Napier Dec 10 '20 at 00:47
  • (this doesn't really answer your question; I'd explore it by creating your own protocol that implements Hashable into your own "Hasher-like" struct. This wouldn't support "arbitrary Hashable" types; you'd have to conform the specific types you need. But I suspect it's your best bet.) – Rob Napier Dec 10 '20 at 00:55
  • @NewDev I think it could. Maybe it would work if we had a custom serializer that would return a hash value instead of a JSON or similar structure. Not having universal hashable support is sadly not an option. – maticzav Dec 10 '20 at 09:07

0 Answers0