-
Notifications
You must be signed in to change notification settings - Fork 30
/
hash.c
65 lines (59 loc) · 1.31 KB
/
hash.c
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
/**
* @file hash.c
* @author hutusi ([email protected])
* @brief Refer to hash.h
* @date 2019-07-26
*
* @copyright Copyright (c) 2019, hutusi.com
*
*/
#include "hash.h"
#include "def.h"
#include "text.h"
unsigned int hash_char(void *pointer)
{
return *(unsigned char *)pointer;
}
unsigned int hash_int(void *pointer)
{
return *(unsigned int *)pointer;
}
unsigned int hash_object(void *object)
{
return (unsigned int)object;
}
/**
* @brief BKDR hash algorithm.
*
* Introduced by Brian Kernighan and Dennis Ritchie in *The C Programming
* Language*
*
* @param string Input string.
* @return unsigned int Return hash.
*/
unsigned int hash_string(void *string)
{
unsigned int hash = 0;
char *p = (char *)string;
while (*p != '\0') {
/** factor 131 also could be 31、131、1313、13131、131313 ... */
hash = hash * 131 + (*p);
++p;
}
return hash;
}
/**
* @brief Same as string hash.
*
* @param text Input text.
* @return unsigned int Return hash.
*/
unsigned int hash_text(void *text)
{
unsigned int hash = 0;
for (unsigned int i =0; i < text_length(text); ++i) {
/** factor 131 also could be 31、131、1313、13131、131313 ... */
hash = hash * 131 + text_char_at(text, i);
}
return hash;
}