@@ -8,35 +8,34 @@ import StdlibUnittest
8
8
9
9
var HashingTestSuite = TestSuite ( " Hashing " )
10
10
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 ,
14
14
_ pValue: Double
15
15
) {
16
+ typealias Output = Int
16
17
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) }
19
20
20
- for inputBit in 0 ..< bits {
21
+ for inputBit in 0 ..< Input . bitWidth {
21
22
// 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)
26
25
for i in testData. indices {
27
26
let inputA = testData [ i]
28
27
let outputA = testDataHashed [ i]
29
28
let inputB = inputA ^ ( 1 << UInt64 ( inputBit) )
30
29
let outputB = hashUnderTest ( inputB)
31
30
var delta = outputA ^ outputB
32
- for outputBit in 0 ..< bits {
31
+ for outputBit in 0 ..< Output . bitWidth {
33
32
if delta & 1 == 1 {
34
33
bitFlips [ outputBit] += 1
35
34
}
36
35
delta = delta >> 1
37
36
}
38
37
}
39
- for outputBit in 0 ..< bits {
38
+ for outputBit in 0 ..< Output . bitWidth {
40
39
expectTrue (
41
40
chiSquaredUniform2 ( testsInBatch, bitFlips [ outputBit] , pValue) ,
42
41
" inputBit: \( inputBit) , outputBit: \( outputBit) " )
@@ -48,11 +47,11 @@ func avalancheTest(
48
47
// White-box testing: assume that the other N-bit to N-bit mixing functions
49
48
// just dispatch to these. (Avalanche test is relatively expensive.)
50
49
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 )
52
51
}
53
52
54
53
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 )
56
55
}
57
56
58
57
runAllTests ( )
0 commit comments