Added 'fold_bits()' to binary.h and used in bloom_filter.h

This commit is contained in:
John Wellbelove 2015-09-10 11:25:17 +01:00
parent 7aa3f81cd9
commit c8e9a2e852
2 changed files with 31 additions and 17 deletions

View File

@ -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 <typename TReturn, const size_t NBITS, typename TValue>
TReturn fold_bits(TValue value)
{
STATIC_ASSERT(integral_limits<TReturn>::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.
//***************************************************************************

View File

@ -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 <typename THash>
size_t get_hash(parameter_t key) const
{
const size_t mask = etl::power_of_2_round_up<WIDTH>::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<etl::power_of_2_round_up<WIDTH>::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<size_t, etl::log2<WIDTH>::value>(hash);
}
/// The Bloom filter flags.