// ConstantTimeByteEq returns 1 if x == y and 0 otherwise.
func ConstantTimeByteEq(x, y uint8) int {
- z := ^(x ^ y)
- z &= z >> 4
- z &= z >> 2
- z &= z >> 1
-
- return int(z)
+ return int((uint32(x^y) - 1) >> 31)
}
// ConstantTimeEq returns 1 if x == y and 0 otherwise.
func ConstantTimeEq(x, y int32) int {
- z := ^(x ^ y)
- z &= z >> 16
- z &= z >> 8
- z &= z >> 4
- z &= z >> 2
- z &= z >> 1
-
- return int(z & 1)
+ return int((uint64(uint32(x^y)) - 1) >> 63)
}
// ConstantTimeCopy copies the contents of y into x (a slice of equal length)
}
}
}
+
+var benchmarkGlobal uint8
+
+func BenchmarkConstantTimeByteEq(b *testing.B) {
+ var x, y uint8
+
+ for i := 0; i < b.N; i++ {
+ x, y = uint8(ConstantTimeByteEq(x, y)), x
+ }
+
+ benchmarkGlobal = x
+}
+
+func BenchmarkConstantTimeEq(b *testing.B) {
+ var x, y int
+
+ for i := 0; i < b.N; i++ {
+ x, y = ConstantTimeEq(int32(x), int32(y)), x
+ }
+
+ benchmarkGlobal = uint8(x)
+}
+
+func BenchmarkConstantTimeLessOrEq(b *testing.B) {
+ var x, y int
+
+ for i := 0; i < b.N; i++ {
+ x, y = ConstantTimeLessOrEq(x, y), x
+ }
+
+ benchmarkGlobal = uint8(x)
+}