From cfb6dd2ea8907f6ff3aaf24bc579c7c2b1d86e90 Mon Sep 17 00:00:00 2001 From: Arkadiy Paronyan Date: Fri, 13 Jan 2017 09:52:23 +0100 Subject: [PATCH] Optimized hash lookups (#4144) * Optimize hash comparison * Use libc --- Cargo.lock | 1 + util/bigint/Cargo.toml | 1 + util/bigint/src/hash.rs | 20 ++++++-------------- util/bigint/src/lib.rs | 1 + 4 files changed, 9 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4f9c48dd7..632048c0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -382,6 +382,7 @@ version = "0.1.2" dependencies = [ "bigint 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "heapsize 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/util/bigint/Cargo.toml b/util/bigint/Cargo.toml index 5fe02865c..5d47713fc 100644 --- a/util/bigint/Cargo.toml +++ b/util/bigint/Cargo.toml @@ -12,6 +12,7 @@ bigint = "1.0" rustc-serialize = "0.3" heapsize = "0.3" rand = "0.3.12" +libc = "0.2" [features] x64asm_arithmetic=[] diff --git a/util/bigint/src/hash.rs b/util/bigint/src/hash.rs index fb9fbbd72..34eff3962 100644 --- a/util/bigint/src/hash.rs +++ b/util/bigint/src/hash.rs @@ -26,6 +26,7 @@ use rand::Rng; use rand::os::OsRng; use rustc_serialize::hex::{FromHex, FromHexError}; use bigint::{Uint, U256}; +use libc::{c_void, memcmp}; /// Trait for a fixed-size byte array to be used as the output of hash functions. pub trait FixedHash: Sized { @@ -214,25 +215,16 @@ macro_rules! impl_hash { impl PartialEq for $from { fn eq(&self, other: &Self) -> bool { - for i in 0..$size { - if self.0[i] != other.0[i] { - return false; - } - } - true + unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) == 0 } } } impl Ord for $from { fn cmp(&self, other: &Self) -> Ordering { - for i in 0..$size { - if self.0[i] > other.0[i] { - return Ordering::Greater; - } else if self.0[i] < other.0[i] { - return Ordering::Less; - } - } - Ordering::Equal + let r = unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) }; + if r < 0 { return Ordering::Less } + if r > 0 { return Ordering::Greater } + return Ordering::Equal; } } diff --git a/util/bigint/src/lib.rs b/util/bigint/src/lib.rs index e394ba7fb..28ab5b10e 100644 --- a/util/bigint/src/lib.rs +++ b/util/bigint/src/lib.rs @@ -21,6 +21,7 @@ extern crate rand; extern crate rustc_serialize; extern crate bigint; +extern crate libc; #[macro_use] extern crate heapsize; pub mod hash;