noq_proto/
constant_time.rs

1// This function is non-inline to prevent the optimizer from looking inside it.
2#[inline(never)]
3fn constant_time_ne(a: &[u8], b: &[u8]) -> u8 {
4    assert!(a.len() == b.len());
5
6    // These useless slices make the optimizer elide the bounds checks.
7    // See the comment in clone_from_slice() added on Rust commit 6a7bc47.
8    let len = a.len();
9    let a = &a[..len];
10    let b = &b[..len];
11
12    let mut tmp = 0;
13    for i in 0..len {
14        tmp |= a[i] ^ b[i];
15    }
16    tmp // The compare with 0 must happen outside this function.
17}
18
19/// Compares byte strings in constant time.
20pub(crate) fn eq(a: &[u8], b: &[u8]) -> bool {
21    a.len() == b.len() && constant_time_ne(a, b) == 0
22}