#[inline]
pub fn ct_eq_bytes(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff: u8 = 0;
for (x, y) in a.iter().zip(b.iter()) {
diff |= x ^ y;
}
core::hint::black_box(diff) == 0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_inputs_are_equal() {
assert!(ct_eq_bytes(b"", b""));
}
#[test]
fn equal_bytes_compare_equal() {
assert!(ct_eq_bytes(b"secret", b"secret"));
}
#[test]
fn different_bytes_compare_unequal() {
assert!(!ct_eq_bytes(b"secret", b"sxcret"));
assert!(!ct_eq_bytes(b"secret", b"secrex"));
}
#[test]
fn different_lengths_compare_unequal() {
assert!(!ct_eq_bytes(b"secret", b"secrets"));
assert!(!ct_eq_bytes(b"", b"x"));
}
}