From e182b3293dcc1cdfd1c3a3d9cae0132077a240b1 Mon Sep 17 00:00:00 2001 From: Tim Hughes Date: Wed, 26 Feb 2014 15:31:58 +0000 Subject: [PATCH] Implement optimised hash and equality operators for h256, and specialise std::hash. --- libethereum/Common.h | 54 ++++++++++++++++++++++++++++---------------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/libethereum/Common.h b/libethereum/Common.h index d1eed99f8..6613b70ba 100644 --- a/libethereum/Common.h +++ b/libethereum/Common.h @@ -145,10 +145,41 @@ public: std::array& asArray() { return m_data; } std::array const& asArray() const { return m_data; } + // generic std::hash compatible function object + struct hash + { + size_t operator()(FixedHash const& value) const + { + size_t h = 0; + for (i: in m_data) h = (h<<5 - h) + i; + return h; + } + }; + private: std::array m_data; }; + +// fast equality for h256 +template<> bool FixedHash<32>::operator==(FixedHash<32> const& _other) const +{ + const uint64_t* hash1 = (const uint64_t*)this->data(); + const uint64_t* hash2 = (const uint64_t*)_other.data(); + return (hash1[0] == hash2[0]) && (hash1[1] == hash2[1]) && (hash1[2] == hash2[2]) && (hash1[3] == hash2[3]); +} + +// fast std::hash compatible hash function object for h256 +template<> size_t FixedHash<32>::hash::operator()(FixedHash<32> const& value) const +{ + const uint64_t*data = (const uint64_t*)value.data(); + uint64_t hash = data[0]; + hash ^= data[1]; + hash ^= data[2]; + hash ^= data[3]; + return (size_t)hash; +} + template inline std::ostream& operator<<(std::ostream& _out, FixedHash const& _h) { @@ -181,26 +212,6 @@ using HexMap = std::map; static const u256 Invalid256 = ~(u256)0; static const bytes NullBytes; -// This is the helper class for the std::unordered_map lookup; it converts the input 256bit hash into a size_t sized hash value -// and does an exact comparison of two hash entries. -class H256Hash -{ -public: - static const size_t bucket_size = 4; - static const size_t min_buckets = 8; - - // Compute the size_t hash of this hash - size_t operator()(const h256 &index) const - { - const uint64_t *data = (const uint64_t *)index.data(); - uint64_t hash = data[0]; - hash ^= data[1]; - hash ^= data[2]; - hash ^= data[3]; - return (size_t)hash; - } -}; - /// Logging class NullOutputStream { @@ -667,3 +678,6 @@ bytes contents(std::string const& _file); void writeFile(std::string const& _file, bytes const& _data); } + +// forward std::hash to eth::h256::hash +template<> struct std::hash : eth::h256::hash {};