-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
universal_hash.h
74 lines (65 loc) · 1.62 KB
/
universal_hash.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*******************************************************************************
* DANIEL'S ALGORITHM IMPLEMENTAIONS
*
* /\ | _ _ ._ o _|_ |_ ._ _ _
* /--\ | (_| (_) | | |_ | | | | | _>
* _|
*
* UNIVERSAL HASH FUNCTION
*
* http://en.wikipedia.org/wiki/Universal_hash
*
******************************************************************************/
#ifndef ALGO_UNIVERSAL_HASH_H__
#define ALGO_UNIVERSAL_HASH_H__
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include "prime.h"
#include "imath.h"
#include "random.h"
#include "integer.h"
namespace alg {
struct UHash {
uint32_t a[KLEN];
uint32_t prime;
};
/**
* init an universal hash struct
*/
static inline void uhash_init(struct UHash * params, uint32_t max_element) {
int i;
// the size of the hash bucket is the prime larger than 2 * max_element
for(i=max_element+1;;i++) {
if (is_prime(i)) {
params->prime = i;
break;
}
}
for (i = 0; i < KLEN;i++) {
params->a[i] = rand()%params->prime;
}
}
/**
* hash a key
*/
static inline uint32_t uhash_integer(const struct UHash * params, uint64_t key) {
uint32_t k[KLEN];
uint32_t sum;
m_based(key, params->prime, k);
sum = dot_product(k,params->a,KLEN);
return sum%params->prime;
}
/**
* hash an arbitrary length integer.
* len, number of 32-bit integer, max len is 32
*/
static uint32_t uhash_bigint(const struct UHash * params, uint32_t * key, uint32_t len) {
// TODO : need a better algorithm, or NOT?
return key[0]%params->prime;
}
}
#endif //