ios - 跨 iOS 版本稳定的 String 哈希值?

标签 ios swift hash nsstring hashcode

在 iOS 的文档 String.hash 中说:

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

(奇怪为什么他们在 iOS 文档中提到 OS X)

好吧,我需要一个不会随 iOS 版本改变的散列函数。它可以很简单,我不需要像 SHA 这样的东西。有一些图书馆吗?

关于这个here还有一个问题但是那里接受的(也是唯一的)答案只是说我们应该尊重文档中的注释。

最佳答案

这是一个用于 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
 }

它有点源自 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
}

不幸的是,两者不会产生相同的散列。为此,您需要反转 strHash 中的迭代器顺序:

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

但这会慢 13 倍,与我从 https://useyourloaf.com/blog/swift-hashable/ 获得的 djb2hash String 扩展有点可比

这里有一些基准,针对一百万次迭代:

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

对于 C++,str2Int 大致与 Swift 3 的 hashValue 一样快:

str2int execution time: 0.136421

关于ios - 跨 iOS 版本稳定的 String 哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35882103/

相关文章:

java - 使用盐散列密码

java - 与纸牌游戏进行映射?

ios - kFIREventViewItem 事件日志参数未显示在 Firebase 控制台中

ios - 文本字段上的位数

ios - 禁用 tabBarController 中项目的旋转

swift - Swift 中通过 Firebase 的赞成票/反对票系统

ios - 呈现警报 Controller 后,Swift 在 TableView(didSelectRowAt IndexPath) 中继续流动

ios - nil 合并运算符 '??' 的左侧具有非可选类型 'String' ,因此从不使用右侧

ios - 在方向更改时自动缩放 UIView 以按比例缩放以适合父 View

php - 确定数组是否关联(散列)