Skip to content

Commit e83018c

Browse files
authored
Merge pull request #15277 from lorentey/avalanche
2 parents afbcbfd + ec15f7e commit e83018c

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

validation-test/stdlib/HashingAvalanche.swift

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,35 +8,34 @@ import StdlibUnittest
88

99
var HashingTestSuite = TestSuite("Hashing")
1010

11-
func avalancheTest(
12-
_ bits: Int,
13-
_ hashUnderTest: @escaping (UInt64) -> UInt64,
11+
func avalancheTest<Input: FixedWidthInteger & UnsignedInteger>(
12+
for type: Input.Type,
13+
_ hashUnderTest: @escaping (Input) -> Int,
1414
_ pValue: Double
1515
) {
16+
typealias Output = Int
1617
let testsInBatch = 100000
17-
let testData = randArray64(testsInBatch)
18-
let testDataHashed = Array(testData.lazy.map { hashUnderTest($0) })
18+
let testData = randArray64(testsInBatch).map { Input(truncatingIfNeeded: $0) }
19+
let testDataHashed = testData.map { hashUnderTest($0) }
1920

20-
for inputBit in 0..<bits {
21+
for inputBit in 0..<Input.bitWidth {
2122
// Using an array here makes the test too slow.
22-
var bitFlips = UnsafeMutablePointer<Int>.allocate(capacity: bits)
23-
for i in 0..<bits {
24-
bitFlips[i] = 0
25-
}
23+
let bitFlips = UnsafeMutablePointer<Int>.allocate(capacity: Output.bitWidth)
24+
bitFlips.initialize(to: 0, count: Output.bitWidth)
2625
for i in testData.indices {
2726
let inputA = testData[i]
2827
let outputA = testDataHashed[i]
2928
let inputB = inputA ^ (1 << UInt64(inputBit))
3029
let outputB = hashUnderTest(inputB)
3130
var delta = outputA ^ outputB
32-
for outputBit in 0..<bits {
31+
for outputBit in 0..<Output.bitWidth {
3332
if delta & 1 == 1 {
3433
bitFlips[outputBit] += 1
3534
}
3635
delta = delta >> 1
3736
}
3837
}
39-
for outputBit in 0..<bits {
38+
for outputBit in 0..<Output.bitWidth {
4039
expectTrue(
4140
chiSquaredUniform2(testsInBatch, bitFlips[outputBit], pValue),
4241
"inputBit: \(inputBit), outputBit: \(outputBit)")
@@ -48,11 +47,11 @@ func avalancheTest(
4847
// White-box testing: assume that the other N-bit to N-bit mixing functions
4948
// just dispatch to these. (Avalanche test is relatively expensive.)
5049
HashingTestSuite.test("_Hasher.append(UInt64)/avalanche") {
51-
avalancheTest(64, { UInt64(truncatingIfNeeded: _hashValue(for: $0)) }, 0.02)
50+
avalancheTest(for: UInt64.self, _hashValue(for:), 0.02)
5251
}
5352

5453
HashingTestSuite.test("_Hasher.append(UInt32)/avalanche") {
55-
avalancheTest(32, { UInt64(truncatingIfNeeded: _hashValue(for: $0)) }, 0.02)
54+
avalancheTest(for: UInt32.self, _hashValue(for:), 0.02)
5655
}
5756

5857
runAllTests()

0 commit comments

Comments
 (0)