Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
//! enable the `core_hint_black_box` feature.
//!
//! Rust versions from 1.51 or higher have const generics support. You may enable
//! `const-generics` feautre to have `subtle` traits implemented for arrays `[T; N]`.
//! `const-generics` feature to have `subtle` traits implemented for arrays `[T; N]`.
//!
//! Versions prior to `2.2` recommended use of the `nightly` feature to enable an
//! optimization barrier; this is not required in versions `2.2` and above.
Expand Down Expand Up @@ -597,6 +597,16 @@ where
}
}

#[cfg(feature = "const-generics")]
impl<T, const N: usize> ConstantTimeEq for [T; N]
where
T: ConstantTimeEq,
{
fn ct_eq(&self, other: &Self) -> Choice {
self.as_slice().ct_eq(other)
}
}

/// A type which can be conditionally negated in constant time.
///
/// # Note
Expand Down
23 changes: 18 additions & 5 deletions tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,42 @@ use subtle::*;
#[test]
#[should_panic]
fn slices_equal_different_lengths() {
let a: [u8; 3] = [0, 0, 0];
let b: [u8; 4] = [0, 0, 0, 0];
let a: &[u8] = &[0, 0, 0];
let b: &[u8] = &[0, 0, 0, 0];

assert_eq!((&a).ct_eq(&b).unwrap_u8(), 1);
}

#[test]
fn slices_equal() {
let a: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
let b: [u8; 8] = [1, 2, 3, 4, 4, 3, 2, 1];
let a: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8];
let b: &[u8] = &[1, 2, 3, 4, 4, 3, 2, 1];

let a_eq_a = (&a).ct_eq(&a);
let a_eq_b = (&a).ct_eq(&b);

assert_eq!(a_eq_a.unwrap_u8(), 1);
assert_eq!(a_eq_b.unwrap_u8(), 0);

let c: [u8; 16] = [0u8; 16];
let c: &[u8] = &[0u8; 16];

let a_eq_c = (&a).ct_eq(&c);
assert_eq!(a_eq_c.unwrap_u8(), 0);
}

#[cfg(feature = "const-generics")]
#[test]
fn arrays_equal() {
let a: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
let b: [u8; 8] = [1, 2, 3, 4, 4, 3, 2, 1];

let a_eq_a = (&a).ct_eq(&a);
let a_eq_b = (&a).ct_eq(&b);

assert_eq!(a_eq_a.unwrap_u8(), 1);
assert_eq!(a_eq_b.unwrap_u8(), 0);
}

#[test]
fn conditional_assign_i32() {
let mut a: i32 = 5;
Expand Down