1 /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 /*
3 * Hash Functions
4 * (C) 2013 Jung-Sang Ahn <jungsang.ahn@gmail.com>
5 */
6
7 #include "hash_functions.h"
8 #include "common.h"
9
10 // djb2 hashing using last LEN digits in VALUE
hash_djb2(uint8_t *value, int len)11 uint32_t hash_djb2(uint8_t *value, int len)
12 {
13 unsigned hash = 5381;
14 while(len--){
15 hash = ((hash << 5) + hash) + *((uint8_t*)value + len);
16 }
17 return hash;
18 }
19
hash_djb2_last8(uint8_t *value, int len)20 uint32_t hash_djb2_last8(uint8_t *value, int len)
21 {
22 int min = MIN(len, 8), c;
23 unsigned hash = 5381;
24 c = min;
25 while(c--){
26 hash = ((hash << 5) + hash) + *((uint8_t*)value + (len - min) + c);
27 }
28 return hash;
29 }
30
31 // LCOV_EXCL_START
hash_uint_modular(uint64_t value, uint64_t mod)32 uint32_t hash_uint_modular(uint64_t value, uint64_t mod)
33 {
34 return value % mod;
35 }
36 // LCOV_EXCL_STOP
37
38 // LCOV_EXCL_START
hash_shuffle_2uint(uint64_t a, uint64_t b)39 uint32_t hash_shuffle_2uint(uint64_t a, uint64_t b)
40 {
41 uint32_t c;
42
43 a ^= bitswap64(a ^ UINT64_C(0xffffffffffffffff));
44 b ^= bitswap64(b ^ UINT64_C(0xffffffffffffffff));
45
46 a = (a & 0xffff) ^ ((a & 0xffff0000) >> 16) ^
47 ((a & UINT64_C(0xffff00000000)) >> 32) ^
48 ((a & UINT64_C(0xffff000000000000)) >> 48);
49 b = (b & 0xffff) ^ ((b & 0xffff0000) >> 16) ^
50 ((b & UINT64_C(0xffff00000000)) >> 32) ^
51 ((b & UINT64_C(0xffff000000000000)) >> 48);
52
53 c = (((a & 0x0000000f) << 0) |
54 ((b & 0x0000000f) << 4) |
55 ((a & 0x000000f0) << 4) |
56 ((b & 0x000000f0) << 8) |
57 ((a & 0x00000f00) << 8) |
58 ((b & 0x00000f00) << 12) |
59 ((a & 0x0000f000) << 12) |
60 ((b & 0x0000f000) << 16));
61
62 return (((c << 5) + c) << 5) + c;
63 }
64 // LCOV_EXCL_STOP
65
66