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

constant time Ord and PartialOrd implementations #267

Open
wants to merge 3 commits into
base: master
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
31 changes: 31 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,37 @@ impl PartialEq<[u8]> for Hash {

impl Eq for Hash {}

/// This implementation is constant-time.
impl PartialOrd for Hash {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}

/// This implementation is constant-time.
impl Ord for Hash {
#[inline]
fn cmp(&self, other: &Hash) -> cmp::Ordering {
let self32: [u32; 8] = platform::words_from_be_bytes_32(&self.0);
let other32: [u32; 8] = platform::words_from_be_bytes_32(&other.0);
let mut acc: i32 = 0;
for i in 0..self32.len() {
// the left shift keeps earlier comparisons more significant than later ones
acc = (acc<<1) + cmp_sign(&self32[i], &other32[i]);
}
acc.cmp(&0)
}
}

/// Compares two items and returns -1 if Less, 0 if Equal, or 1 if Greater.
fn cmp_sign<T: Ord>(a: &T, b: &T) -> i32 {
match a.cmp(b) {
cmp::Ordering::Less => -1,
cmp::Ordering::Equal => 0,
cmp::Ordering::Greater => 1,
}
}

impl fmt::Display for Hash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Formatting field as `&str` to reduce code size since the `Debug`
Expand Down
9 changes: 9 additions & 0 deletions src/platform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,15 @@ pub fn sse2_detected() -> bool {
false
}

#[inline(always)]
pub fn words_from_be_bytes_32(bytes: &[u8; 32]) -> [u32; 8] {
let mut out: [u32; 8] = [0; 8];
for i in 0..8 {
out[i] = u32::from_be_bytes(*(array_ref!(bytes, 4*i, 4)));
}
out
}

#[inline(always)]
pub fn words_from_le_bytes_32(bytes: &[u8; 32]) -> [u32; 8] {
let mut out = [0; 8];
Expand Down
11 changes: 11 additions & 0 deletions src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -594,3 +594,14 @@ fn test_issue_206_windows_sse2() {
assert_eq!(crate::Hasher::new().update(input).finalize(), expected_hash);
}
}

#[test]
#[cfg(feature = "std")]
fn test_order_match() {
let hashes = [[0], [1], [2], [3]].map(|a| reference_hash(&a));
for i in 0..hashes.len() {
for j in 0..hashes.len() {
assert_eq!(hashes[i].cmp(&hashes[j]), hashes[i].0.cmp(&hashes[j].0));
}
}
}