1//! Constant-time utilities.
2use subtle::{Choice, ConstantTimeEq};
34/// Convert a boolean into a Choice.
5///
6/// This isn't necessarily a good idea or constant-time.
7pub(crate) fn bool_to_choice(v: bool) -> Choice {
8 Choice::from(u8::from(v))
9}
1011/// Return true if two slices are equal. Performs its operation in constant
12/// time, but returns a bool instead of a subtle::Choice.
13pub(crate) fn bytes_eq(a: &[u8], b: &[u8]) -> bool {
14let choice = a.ct_eq(b);
15 choice.unwrap_u8() == 1
16}
1718/// Returns true if all bytes of the input are zero (including if the slice is
19/// empty). Executes in constant time for a given length of input.
20pub(crate) fn is_zero(x: &[u8]) -> bool {
21// It's tempting to lift the Choice out of the fold loop, s.t. the loop does
22 // a simple bit-or of each byte, but then the compiler could theoretically
23 // exit the loop early if all bits become one (i.e. 0xff). (Granted this
24 // seems unlikely in practice)
25x.iter()
26 .map(|b| bool_to_choice(*b == 0))
27 .fold(bool_to_choice(true), std::ops::BitAnd::bitand)
28 .unwrap_u8()
29 == 1
30}
3132#[cfg(test)]
33mod test {
34// @@ begin test lint list maintained by maint/add_warning @@
35#![allow(clippy::bool_assert_comparison)]
36 #![allow(clippy::clone_on_copy)]
37 #![allow(clippy::dbg_macro)]
38 #![allow(clippy::mixed_attributes_style)]
39 #![allow(clippy::print_stderr)]
40 #![allow(clippy::print_stdout)]
41 #![allow(clippy::single_char_pattern)]
42 #![allow(clippy::unwrap_used)]
43 #![allow(clippy::unchecked_duration_subtraction)]
44 #![allow(clippy::useless_vec)]
45 #![allow(clippy::needless_pass_by_value)]
46//! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
47#[test]
48fn test_bytes_eq() {
49use super::bytes_eq;
50assert!(bytes_eq(&b"123"[..], &b"1234"[..3]));
51assert!(!bytes_eq(&b"123"[..], &b"1234"[..]));
52assert!(bytes_eq(&b"45"[..], &b"45"[..]));
53assert!(!bytes_eq(&b"hi"[..], &b"45"[..]));
54assert!(bytes_eq(&b""[..], &b""[..]));
55 }
5657#[test]
58fn test_is_zero() {
59use super::is_zero;
60assert!(is_zero(&[]));
61assert!(is_zero(&[0]));
62assert!(is_zero(&[0, 0]));
63assert!(!is_zero(&[1, 0]));
64assert!(!is_zero(&[0, 1]));
65assert!(!is_zero(&[0, 1, 0]));
66 }
67}