Skip to content

[test] Update hash avalanche test #15277

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 16, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 13 additions & 14 deletions validation-test/stdlib/HashingAvalanche.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,34 @@ import StdlibUnittest

var HashingTestSuite = TestSuite("Hashing")

func avalancheTest(
_ bits: Int,
_ hashUnderTest: @escaping (UInt64) -> UInt64,
func avalancheTest<Input: FixedWidthInteger & UnsignedInteger>(
for type: Input.Type,
_ hashUnderTest: @escaping (Input) -> Int,
_ pValue: Double
) {
typealias Output = Int
let testsInBatch = 100000
let testData = randArray64(testsInBatch)
let testDataHashed = Array(testData.lazy.map { hashUnderTest($0) })
let testData = randArray64(testsInBatch).map { Input(truncatingIfNeeded: $0) }
let testDataHashed = testData.map { hashUnderTest($0) }

for inputBit in 0..<bits {
for inputBit in 0..<Input.bitWidth {
// Using an array here makes the test too slow.
var bitFlips = UnsafeMutablePointer<Int>.allocate(capacity: bits)
for i in 0..<bits {
bitFlips[i] = 0
}
let bitFlips = UnsafeMutablePointer<Int>.allocate(capacity: Output.bitWidth)
bitFlips.initialize(to: 0, count: Output.bitWidth)
for i in testData.indices {
let inputA = testData[i]
let outputA = testDataHashed[i]
let inputB = inputA ^ (1 << UInt64(inputBit))
let outputB = hashUnderTest(inputB)
var delta = outputA ^ outputB
for outputBit in 0..<bits {
for outputBit in 0..<Output.bitWidth {
if delta & 1 == 1 {
bitFlips[outputBit] += 1
}
delta = delta >> 1
}
}
for outputBit in 0..<bits {
for outputBit in 0..<Output.bitWidth {
expectTrue(
chiSquaredUniform2(testsInBatch, bitFlips[outputBit], pValue),
"inputBit: \(inputBit), outputBit: \(outputBit)")
Expand All @@ -48,11 +47,11 @@ func avalancheTest(
// White-box testing: assume that the other N-bit to N-bit mixing functions
// just dispatch to these. (Avalanche test is relatively expensive.)
HashingTestSuite.test("_Hasher.append(UInt64)/avalanche") {
avalancheTest(64, { UInt64(truncatingIfNeeded: _hashValue(for: $0)) }, 0.02)
avalancheTest(for: UInt64.self, _hashValue(for:), 0.02)
}

HashingTestSuite.test("_Hasher.append(UInt32)/avalanche") {
avalancheTest(32, { UInt64(truncatingIfNeeded: _hashValue(for: $0)) }, 0.02)
avalancheTest(for: UInt32.self, _hashValue(for:), 0.02)
}

runAllTests()