Skip to content

Commit eef1cf6

Browse files
committed
Add result checking to the ChaCha benchmark.
This benchmark was being miscompiled for some time and we did not catch it. I only noticed because a correcteness fix caused a regression.
1 parent 2544806 commit eef1cf6

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

benchmark/single-source/ChaCha.swift

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import TestsUtils
2222
enum ChaCha20 { }
2323

2424
extension ChaCha20 {
25+
@inline(never)
2526
public static func encrypt<Key: Collection, Nonce: Collection, Bytes: MutableCollection>(bytes: inout Bytes, key: Key, nonce: Nonce, initialCounter: UInt32 = 0) where Bytes.Element == UInt8, Key.Element == UInt8, Nonce.Element == UInt8 {
2627
var baseState = ChaChaState(key: key, nonce: nonce, counter: initialCounter)
2728
var index = bytes.startIndex
@@ -347,13 +348,28 @@ public let ChaCha = BenchmarkInfo(
347348
runFunction: run_ChaCha,
348349
tags: [.runtime, .cpubench])
349350

351+
@inline(never)
352+
func checkResult(_ plaintext: [UInt8]) {
353+
CheckResults(plaintext.first! == 6 && plaintext.last! == 254)
354+
var hash: UInt64 = 0
355+
for byte in plaintext {
356+
// rotate
357+
hash = (hash &<< 8) | (hash &>> (64 - 8))
358+
hash ^= UInt64(byte)
359+
}
360+
CheckResults(hash == 0xa1bcdb217d8d14e4)
361+
}
350362

351363
@inline(never)
352364
public func run_ChaCha(_ N: Int) {
353-
var plaintext = Array(repeating: UInt8(0), count: 30720) // Chosen for CI runtime
354365
let key = Array(repeating: UInt8(1), count: 32)
355366
let nonce = Array(repeating: UInt8(2), count: 12)
356367

368+
var checkedtext = Array(repeating: UInt8(0), count: 1024)
369+
ChaCha20.encrypt(bytes: &checkedtext, key: key, nonce: nonce)
370+
checkResult(checkedtext)
371+
372+
var plaintext = Array(repeating: UInt8(0), count: 30720) // Chosen for CI runtime
357373
for _ in 1...N {
358374
ChaCha20.encrypt(bytes: &plaintext, key: key, nonce: nonce)
359375
blackHole(plaintext.first!)

0 commit comments

Comments
 (0)