String hash value that will be stable in iOS versions?

The String.hash documentation for iOS says:

You should not rely on this property having the same hash value in OS X releases.

(weird why they talk about OS X in the iOS documentation)

Well, I need a hasshing function that will not change with the release of iOS. It could be simple, I don’t need anything like SHA. Is there a library for this?

There is another question about this, but the accepted (and only) answer simply states that we must follow the note in the documentation.

+10
source share
1 answer

Here is the unencrypted hash for Swift 3:

  func strHash(_ str: String) -> UInt64 { var result = UInt64 (5381) let buf = [UInt8](str.utf8) for b in buf { result = 127 * (result & 0x00ffffffffffffff) + UInt64(b) } return result } 

This was obtained somewhat from C ++ 11 constexpr

  constexpr uint64_t str2int(char const *input) { return *input // test for null terminator ? (static_cast<uint64_t>(*input) + // add char to end 127 * ((str2int(input + 1) // prime 127 shifts left almost 7 bits & 0x00ffffffffffffff))) // mask right 56 bits : 5381; // start with prime number 5381 } 

Unfortunately, the two do not give the same hash. To do this, you need to change the order of iterators in strHash:

 for b in buf.reversed() {...} 

But this will work 13 times slower, which is somewhat comparable to the djb2hash String extension, which I got from https://useyourloaf.com/blog/swift-hashable/

Here are a few tests per million iterations:

 hashValue execution time: 0.147760987281799 strHash execution time: 1.45974600315094 strHashReversed time: 18.7755110263824 djb2hash execution time: 16.0091370344162 sdbmhash crashed 

For C ++, str2Int is about as fast as Swift 3 hashValue:

 str2int execution time: 0.136421 
+13
source

All Articles