hash: cleanup fletcher

This commit is contained in:
Danny Robson 2014-09-11 15:44:03 +10:00
parent 018fcef146
commit 37ed0fc5fd
3 changed files with 24 additions and 12 deletions

View File

@ -24,14 +24,17 @@
static const unsigned MODULUS = 65521; static const unsigned MODULUS = 65521;
//-----------------------------------------------------------------------------
uint32_t uint32_t
adler32 (const void* restrict _data, size_t _size) adler32 (const void* restrict _data, size_t _size)
{ return fletcher<32, MODULUS, 1, 0> (_data, _size); } {
return adler32 ((uint8_t*)_data, (uint8_t*)_data + _size);
}
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
uint32_t uint32_t
adler32 (const uint8_t *first, const uint8_t *last) adler32 (const uint8_t *first, const uint8_t *last)
{ {
return adler32 (first, last - first); return fletcher<32, MODULUS, 1, 0> (first, last - first);
} }

View File

@ -26,19 +26,27 @@
#include <cstdlib> #include <cstdlib>
template <unsigned BITS, unsigned MODULUS, unsigned INITIAL_A, unsigned INITIAL_B> template <
typename bits_type<BITS>::uint unsigned OUTPUT,
fletcher (const void *restrict _data, size_t size) { unsigned MODULUS,
const uint8_t *restrict data = static_cast<const uint8_t*> (_data); unsigned INITIAL_A,
typename bits_type<BITS>::uint A = INITIAL_A, unsigned INITIAL_B
B = INITIAL_B; >
typename bits_type<OUTPUT>::uint
fletcher (const void *restrict _data,
size_t size)
{
typedef typename bits_type<OUTPUT / 2>::uint temp_t;
auto data = static_cast<const uint8_t*> (_data);
temp_t A = INITIAL_A, B = INITIAL_B;
for (size_t i = 0; i < size; ++i) { for (size_t i = 0; i < size; ++i) {
A = (A + data[i]) % MODULUS; A = (A + data[i]) % MODULUS;
B = (A + B) % MODULUS; B = (A + B) % MODULUS;
} }
return (B << (BITS / 2)) | A; return (B << (OUTPUT / 2u)) + A;
} }
#endif #endif

View File

@ -18,7 +18,8 @@ static const struct {
const char *data; const char *data;
size_t size; size_t size;
} TESTS[] = { } TESTS[] = {
{ 0xDF5B150C, 0x52FB, ALPHABET, strlen (ALPHABET) } { 0xDF5B150C, 0x52FB, ALPHABET, strlen (ALPHABET) },
{ 0x11E60398, 0x3DC8, "Wikipedia", strlen ("Wikipedia") }
}; };
@ -26,7 +27,7 @@ int
main (int, char**) { main (int, char**) {
for (unsigned i = 0; i < elems (TESTS); ++i) { for (unsigned i = 0; i < elems (TESTS); ++i) {
CHECK_EQ (TESTS[i].adler, adler32 (TESTS[i].data, TESTS[i].size)); CHECK_EQ (TESTS[i].adler, adler32 (TESTS[i].data, TESTS[i].size));
CHECK_EQ (TESTS[i].bsd, bsdsum (TESTS[i].data, TESTS[i].size)); CHECK_EQ (TESTS[i].bsd, bsdsum (TESTS[i].data, TESTS[i].size));
} }
return EXIT_SUCCESS; return EXIT_SUCCESS;