Qui è un hash non cripto, per 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
}
'stato derivato da un po 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
}
Sfortunatamente, i due non cedere la stesso hash. Per fare questo si avrebbe bisogno di invertire l'ordine iteratore in strHash:
for b in buf.reversed() {...}
Ma che verrà eseguito 13x più lento, in qualche modo paragonabile all'estensione djb2hash String che ho ricevuto da https://useyourloaf.com/blog/swift-hashable/
Qui ci sono alcuni punti di riferimento, per un milione di iterazioni:
hashValue execution time: 0.147760987281799
strHash execution time: 1.45974600315094
strHashReversed time: 18.7755110263824
djb2hash execution time: 16.0091370344162
sdbmhash crashed
per C++, lo str2Int è più o meno veloce come hashValue Swift 3 di:
str2int execution time: 0.136421
fonte
2017-03-31 20:53:44
se può essere semplice, perché non utilizzare un [MDh hash] (http://stackoverflow.com/a/2018626/1219956) modifica: [versione rapida] (http://stackoverflow.com/questions/24123518/ how-to-use-cc-md5-method-in-swift-language) – Fonix
@Fonix Sì, quella potrebbe essere la soluzione. Ci sono molte risposte alla domanda che stai collegando: potresti raccomandare qualcuno di quelli con un'implementazione hash MD5 stabile e veloce in Swift? – drasto
vedi il secondo link nel mio primo commento, ma per il resto ci sono tonnellate di soluzioni con un rapido google – Fonix