Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement string comparison #115

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
14 changes: 14 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,20 @@ impl<T: ConstantTimeEq> 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 {
Expand Down
7 changes: 7 additions & 0 deletions tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down