From c8e9a2e8528eda700ad2c35eca4d461fa458a132 Mon Sep 17 00:00:00 2001 From: John Wellbelove Date: Thu, 10 Sep 2015 11:25:17 +0100 Subject: [PATCH] Added 'fold_bits()' to binary.h and used in bloom_filter.h --- binary.h | 29 +++++++++++++++++++++++++++++ bloom_filter.h | 19 ++----------------- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/binary.h b/binary.h index 23e82a40..6f32782c 100644 --- a/binary.h +++ b/binary.h @@ -37,6 +37,8 @@ SOFTWARE. #include "type_traits.h" #include "integral_limits.h" #include "static_assert.h" +#include "log.h" +#include "power.h" namespace etl { @@ -421,6 +423,33 @@ namespace etl return (0x69966996 >> value) & 1; } + //*************************************************************************** + /// Fold a binary number down to a set number of bits using XOR. + //*************************************************************************** + template + TReturn fold_bits(TValue value) + { + STATIC_ASSERT(integral_limits::bits >= NBITS, "Return type too small to hold result"); + + const size_t mask = etl::power<2, NBITS>::value - 1; + const size_t shift = NBITS; + + // Fold the value down to fit the width. + TReturn folded_value = 0; + + // Keep shifting down and XORing the lower bits. + while (value >= NBITS) + { + folded_value ^= value & mask; + value >>= shift; + } + + // Fold the remaining bits. + folded_value ^= value; + + return folded_value; + } + //*************************************************************************** /// 8 bit binary constants. //*************************************************************************** diff --git a/bloom_filter.h b/bloom_filter.h index b25f075e..18086b86 100644 --- a/bloom_filter.h +++ b/bloom_filter.h @@ -33,6 +33,7 @@ SOFTWARE. #include "parameter_type.h" #include "bitset.h" #include "type_traits.h" +#include "binary.h" #include "log.h" #include "power.h" @@ -172,26 +173,10 @@ namespace etl template size_t get_hash(parameter_t key) const { - const size_t mask = etl::power_of_2_round_up::value - 1; - size_t hash = THash()(key); // Fold the hash down to fit the width. - size_t folded_hash = 0; - - const size_t shift = etl::log2::value>::value; - - // Keep shifting down and XORing the lower bits. - while (hash >= WIDTH) - { - folded_hash ^= hash & mask; - hash >>= shift; - } - - // Fold the remaining bits. - folded_hash ^= hash; - - return folded_hash; + return fold_bits::value>(hash); } /// The Bloom filter flags.