diff --git a/src/lib.rs b/src/lib.rs index 795eade..da5cd85 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -341,6 +341,20 @@ impl ConstantTimeEq for [T] { } } +impl ConstantTimeEq for str { + /// Check whether two strings are equal. + /// + /// # Note + /// + /// This function short-circuits if the lengths of the input strings + /// are different. Otherwise, it should execute in time independent + /// of the values. + #[inline] + fn ct_eq(&self, rhs: &Self) -> Choice { + self.as_bytes().ct_eq(rhs.as_bytes()) + } +} + impl ConstantTimeEq for Choice { #[inline] fn ct_eq(&self, rhs: &Choice) -> Choice { diff --git a/tests/mod.rs b/tests/mod.rs index f6b3982..90b7cb1 100644 --- a/tests/mod.rs +++ b/tests/mod.rs @@ -31,6 +31,13 @@ fn slices_equal() { assert_eq!(a_eq_c.unwrap_u8(), 0); } +#[test] +fn str_equal() { + assert_eq!("".ct_eq("").unwrap_u8(), 1); + assert_eq!("xxx".ct_eq("xxxx").unwrap_u8(), 0); + assert_eq!("abcd".ct_eq("abcd").unwrap_u8(), 1); +} + #[test] fn conditional_assign_i32() { let mut a: i32 = 5;