68 lines
1.7 KiB
Swift
68 lines
1.7 KiB
Swift
|
|
import Foundation
|
||
|
|
import CXXHash
|
||
|
|
|
||
|
|
/// XXH3 64/128 via vendored official xxHash v0.8.2 (BSD-2).
|
||
|
|
public enum XXH3 {
|
||
|
|
|
||
|
|
public struct Hash128: Equatable, Sendable {
|
||
|
|
public let low64: UInt64
|
||
|
|
public let high64: UInt64
|
||
|
|
|
||
|
|
public var hexString: String {
|
||
|
|
String(format: "%016lx%016lx", high64, low64)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public static func hash64(_ data: Data) -> UInt64 {
|
||
|
|
data.withUnsafeBytes { buf in
|
||
|
|
cxx_xxh3_64(buf.baseAddress, buf.count)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public static func hash128(_ data: Data) -> Hash128 {
|
||
|
|
let h = data.withUnsafeBytes { buf in
|
||
|
|
cxx_xxh3_128(buf.baseAddress, buf.count)
|
||
|
|
}
|
||
|
|
return Hash128(low64: h.low64, high64: h.high64)
|
||
|
|
}
|
||
|
|
|
||
|
|
public static func hexString64(_ v: UInt64) -> String {
|
||
|
|
String(format: "%016lx", v)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Streaming state.
|
||
|
|
public final class Streaming {
|
||
|
|
public enum Bits {
|
||
|
|
case h64
|
||
|
|
case h128
|
||
|
|
}
|
||
|
|
|
||
|
|
private let state: OpaquePointer?
|
||
|
|
private let bits: Bits
|
||
|
|
|
||
|
|
public init(bits: Bits) {
|
||
|
|
self.bits = bits
|
||
|
|
state = cxx_xxh3_create(bits == .h128 ? 1 : 0)
|
||
|
|
}
|
||
|
|
|
||
|
|
deinit {
|
||
|
|
cxx_xxh3_free(state)
|
||
|
|
}
|
||
|
|
|
||
|
|
public func update(_ data: Data) {
|
||
|
|
data.withUnsafeBytes { buf in
|
||
|
|
cxx_xxh3_update(state, buf.baseAddress, buf.count)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public func digest64() -> UInt64 {
|
||
|
|
cxx_xxh3_digest64(state)
|
||
|
|
}
|
||
|
|
|
||
|
|
public func digest128() -> Hash128 {
|
||
|
|
let h = cxx_xxh3_digest128(state)
|
||
|
|
return Hash128(low64: h.low64, high64: h.high64)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|