Make string hash functions return UInt64 based.

- These are used to produce a stable hash, so we want all platforms to produce the same hash value, therefore we use UInt64
This commit is contained in:
Christian Treffs 2020-07-09 22:25:10 +02:00
parent 259643cd8e
commit ed182eb425
No known key found for this signature in database
GPG Key ID: 49A4B4B460BE3ED4
1 changed files with 8 additions and 8 deletions

View File

@ -91,10 +91,10 @@ public enum StringHashing {
/// ///
/// <https://stackoverflow.com/a/43149500> /// <https://stackoverflow.com/a/43149500>
public static func singer_djb2(_ utf8String: String) -> UInt64 { public static func singer_djb2(_ utf8String: String) -> UInt64 {
var hash = UInt64(5381) var hash: UInt64 = 5381
var iter = utf8String.unicodeScalars.makeIterator() var iter = utf8String.unicodeScalars.makeIterator()
while let char = iter.next() { while let char = iter.next() {
hash = 127 * (hash & 0x00ffffffffffffff) &+ UInt64(char.value) hash = 127 * (hash & 0xFFFFFFFFFFFFFF) &+ UInt64(char.value)
} }
return hash return hash
} }
@ -106,11 +106,11 @@ public enum StringHashing {
/// The magic of number 33 (why it works better than many other constants, prime or not) has never been adequately explained. /// The magic of number 33 (why it works better than many other constants, prime or not) has never been adequately explained.
/// ///
/// <http://www.cse.yorku.ca/~oz/hash.html> /// <http://www.cse.yorku.ca/~oz/hash.html>
public static func bernstein_djb2(_ string: String) -> UInt { public static func bernstein_djb2(_ string: String) -> UInt64 {
var hash: UInt = 5381 var hash: UInt64 = 5381
var iter = string.unicodeScalars.makeIterator() var iter = string.unicodeScalars.makeIterator()
while let char = iter.next() { while let char = iter.next() {
hash = (hash << 5) &+ hash &+ UInt(char.value) hash = (hash << 5) &+ hash &+ UInt64(char.value)
} }
return hash return hash
} }
@ -122,11 +122,11 @@ public enum StringHashing {
/// It also happens to be a good general hashing function with good distribution. /// It also happens to be a good general hashing function with good distribution.
/// ///
/// <http://www.cse.yorku.ca/~oz/hash.html> /// <http://www.cse.yorku.ca/~oz/hash.html>
public static func sdbm(_ string: String) -> UInt { public static func sdbm(_ string: String) -> UInt64 {
var hash: UInt = 0 var hash: UInt64 = 0
var iter = string.unicodeScalars.makeIterator() var iter = string.unicodeScalars.makeIterator()
while let char = iter.next() { while let char = iter.next() {
hash = (UInt(char.value) &+ (hash << 6) &+ (hash << 16)) hash = (UInt64(char.value) &+ (hash << 6) &+ (hash << 16))
} }
return hash return hash
} }