28 lines
791 B
C++
28 lines
791 B
C++
|
|
#include "PearsonHash.h"
|
|
|
|
|
|
|
|
// Permutation function for Pearson hashing (uses less space than a lookup table)
|
|
// Needs to be bijective, which it is
|
|
uint8_t PearsonHash::_pearsonPermutation(uint8_t n) {
|
|
return (n*121) % 256;
|
|
}
|
|
|
|
|
|
uint16_t PearsonHash::calcHash16(const void* data, uint16_t len) {
|
|
uint8_t h[2] = { _pearsonPermutation((((uint8_t*)data)[0]+1)%256), _pearsonPermutation(((uint8_t*)data)[0]) };
|
|
for (uint16_t i = 0; i < len; i++) {
|
|
auto _tmp = h[0];
|
|
h[0] = _pearsonPermutation(h[1] ^ ((uint8_t*)data)[i]);
|
|
h[1] = _pearsonPermutation(_tmp ^ ((uint8_t*)data)[i]);
|
|
}
|
|
void* _tmp = h; // To avoid the type punning warning
|
|
return *((uint16_t*)_tmp);
|
|
}
|
|
|
|
|
|
bool PearsonHash::checkHash16(uint16_t crc, const void* data, uint16_t len) {
|
|
return crc == calcHash16(data, len);
|
|
}
|