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;
//-----------------------------------------------------------------------------
uint32_t
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
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>
template <unsigned BITS, unsigned MODULUS, unsigned INITIAL_A, unsigned INITIAL_B>
typename bits_type<BITS>::uint
fletcher (const void *restrict _data, size_t size) {
const uint8_t *restrict data = static_cast<const uint8_t*> (_data);
typename bits_type<BITS>::uint A = INITIAL_A,
B = INITIAL_B;
template <
unsigned OUTPUT,
unsigned MODULUS,
unsigned INITIAL_A,
unsigned 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) {
A = (A + data[i]) % MODULUS;
B = (A + B) % MODULUS;
}
return (B << (BITS / 2)) | A;
return (B << (OUTPUT / 2u)) + A;
}
#endif

View File

@ -14,11 +14,12 @@ static const char *ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW
static const struct {
uint32_t adler;
uint16_t bsd;
const char *data;
size_t size;
} TESTS[] = {
{ 0xDF5B150C, 0x52FB, ALPHABET, strlen (ALPHABET) }
{ 0xDF5B150C, 0x52FB, ALPHABET, strlen (ALPHABET) },
{ 0x11E60398, 0x3DC8, "Wikipedia", strlen ("Wikipedia") }
};
@ -26,7 +27,7 @@ int
main (int, char**) {
for (unsigned i = 0; i < elems (TESTS); ++i) {
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;