Files
externals/linux/include/ActivMiddleware/Misc/HashedDistributionHelper.h
T

90 lines
2.8 KiB
C++

/**
* @file include/ActivMiddleware/Misc/HashedDistributionHelper.h
*
* @brief Header file for the hashed distribution helper class.
*/
#if (!defined ACTIV_MISC_HASHED_DISTRIBUTION_HELPER_H)
#define ACTIV_MISC_HASHED_DISTRIBUTION_HELPER_H
#include "ActivMiddleware/ActivMiddleware.h"
#include "ActivMiddleware/ActivBase/Crc32Generator.h"
#include ACTIV_BOOST_INCLUDE(array.hpp)
//! Activ namespace.
namespace Activ
{
/**
* @brief Hashed distribution helper class.
*
* @tparam PADDING_LENGTH, strings shorter than PADDING_LENGTH are padded with zeros.
* @tparam NUMBER_OF_BITS, the number of bits of the hash to use for the distribution.
* @tparam SEPARATOR, a separator indicating the last character that should be used in the hash calculation.
*/
template<size_t PADDING_LENGTH, uint32_t NUMBER_OF_BITS, const char SEPARATOR>
class HashedDistributionHelper
{
public:
ACTIV_BOOST_STATIC_ASSERT_MSG((NUMBER_OF_BITS <= 32), "NUMBER_OF_BITS can't exceed 32.");
//! Default constructor.
HashedDistributionHelper();
/**
* @brief Get index.
*
* @param string
* @param splitCount
*
* @return The index for this string. Must be < splitCount.
*/
size_t GetIndex(const String &string, const size_t splitCount) const;
private:
static const uint32_t BIT_MASK = BitTraits<NUMBER_OF_BITS>::maxValue;
Crc32Generator<> m_crc32Generator;
Boost::array<uint8_t, PADDING_LENGTH> m_zerosBuffer;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<size_t PADDING_LENGTH, uint32_t NUMBER_OF_BITS, const char SEPARATOR>
HashedDistributionHelper<PADDING_LENGTH, NUMBER_OF_BITS, SEPARATOR>::HashedDistributionHelper() :
m_zerosBuffer()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<size_t PADDING_LENGTH, uint32_t NUMBER_OF_BITS, const char SEPARATOR>
inline size_t HashedDistributionHelper<PADDING_LENGTH, NUMBER_OF_BITS, SEPARATOR>::GetIndex(const String &string,
const size_t splitCount) const
{
// To be correct the search for SEPARATOR should be a reverse search however, a forward search is done here to match
// the MPU implementation.
uint32_t crc = 0;
const size_t separatorIndex = string.find(SEPARATOR);
const size_t usableStringLength = (String::npos != separatorIndex) ? (separatorIndex + 1) : string.length();
if (usableStringLength < PADDING_LENGTH)
{
crc = m_crc32Generator(string.data(), usableStringLength, 0);
crc = m_crc32Generator(&m_zerosBuffer[0], (PADDING_LENGTH - usableStringLength), crc);
}
else
{
crc = m_crc32Generator(string.data(), PADDING_LENGTH, 0);
}
return static_cast<size_t>((crc & BIT_MASK) % splitCount);
}
} // namespace Activ
#endif // (!defined ACTIV_MISC_HASHED_DISTRIBUTION_HELPER_H)