Skip to content

Commit

Permalink
Avoid unaligned loads in stringtable.c hash function
Browse files Browse the repository at this point in the history
On some architectures unaligned loads may not work at all,
e.g. older ARM CPUs return corrupted data on unaligned loads.
  • Loading branch information
jpf91 committed Mar 18, 2014
1 parent 32b1a96 commit 85e87c6
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/root/stringtable.c
Expand Up @@ -21,6 +21,13 @@ hash_t calcHash(const char *str, size_t len)
{
hash_t hash = 0;

union
{
uint8_t scratchB[4];
uint16_t scratchS[2];
uint32_t scratchI;
};

while (1)
{
switch (len)
Expand All @@ -35,18 +42,26 @@ hash_t calcHash(const char *str, size_t len)

case 2:
hash *= 37;
hash += *(const uint16_t *)str;
scratchB[0] = str[0];
scratchB[1] = str[1];
hash += scratchS[0];
return hash;

case 3:
hash *= 37;
hash += (*(const uint16_t *)str << 8) +
scratchB[0] = str[0];
scratchB[1] = str[1];
hash += (scratchS[0] << 8) +
((const uint8_t *)str)[2];
return hash;

default:
hash *= 37;
hash += *(const uint32_t *)str;
scratchB[0] = str[0];
scratchB[1] = str[1];
scratchB[2] = str[2];
scratchB[3] = str[3];
hash += scratchI;
str += 4;
len -= 4;
break;
Expand Down

0 comments on commit 85e87c6

Please sign in to comment.