【发布时间】:2020-01-06 18:53:08
【问题描述】:
我在 Flutter 应用程序中错误地依赖 String.hashCode 的值并将其存储在服务器端。现在我希望能够在 nodeJS 中计算一个字符串的哈希码并得到与 dart 相同的结果...
我怎样才能实现它?在dart中没有找到String.hashCode的实际实现。
【问题讨论】:
我在 Flutter 应用程序中错误地依赖 String.hashCode 的值并将其存储在服务器端。现在我希望能够在 nodeJS 中计算一个字符串的哈希码并得到与 dart 相同的结果...
我怎样才能实现它?在dart中没有找到String.hashCode的实际实现。
【问题讨论】:
String.hashCode的vm实现可以在github上的sdk repo中找到(https://github.com/dart-lang/sdk):
例子:
【讨论】:
这是一个简单的 Swift 实现,它应该为 iOS 和 Flutter 中的简单字符串返回相同的 hashCode 值:
extension String {
func hashCode() -> UInt32 {
var hash: UInt32 = 0
for i in unicodeScalars.filter({ $0.isASCII }).map({ $0.value }) {
hash = hash &+ i
hash = hash &+ (hash << 10)
hash = hash ^ (hash >> 6)
}
hash = hash &+ (hash << 3)
hash = hash ^ (hash >> 11)
hash = hash &+ (hash << 15)
hash = hash & ((1 << 30) &- 1)
return (hash == 0) ? 1 : hash
}
}
【讨论】: