-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_map(str,int).c
125 lines (84 loc) · 2.74 KB
/
hash_map(str,int).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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include "hash_map(str,int).h"
#include "upc_assert_message.h"
#include "hash_func_str.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void* hash_map_str_int_entry_key(struct hash_trait* trait, struct hash_node* node)
{
ASSERT_MESSAGE((NULL != trait), "由外部保证 trait 参数的有效性");
ASSERT_MESSAGE((NULL != node), "由外部保证 node 参数的有效性");
struct hash_map_str_int_entry* entry = (struct hash_map_str_int_entry*)node;
return &(entry->key);
}
static uint32 hash_map_str_int_entry_hash(struct hash_trait* trait, void* key)
{
ASSERT_MESSAGE((NULL != trait), "由外部保证 trait 参数的有效性");
ASSERT_MESSAGE((NULL != key), "由外部保证 key.data 有效性");
struct hash_map_str_key* entry_key = (struct hash_map_str_key*)(key);
return entry_key->hash;
}
static int32 hash_map_str_int_entry_equal(struct hash_trait* trait, void* key1, void* key2)
{
struct hash_map_str_key* entry_key1 = (struct hash_map_str_key*)(key1);
struct hash_map_str_key* entry_key2 = (struct hash_map_str_key*)(key2);
return (entry_key1->hash == entry_key2->hash) && (0 == strcmp(entry_key1->key, entry_key2->key));
}
void hash_map_str_int_entry_del(struct hash_map_str_int_entry* entry)
{
if (NULL == entry)
{
return;
}
if (NULL != entry->key.key)
{
free(entry->key.key);
}
free(entry);
}
struct hash_map_str_key* hash_map_str_key_init(struct hash_map_str_key* key, char* str)
{
ASSERT_MESSAGE((NULL != key), "key 必须由外部保证有效性");
str = (NULL == str)?"":str;
size_t key_len = strlen(str) + 1;
key->key = (char*)malloc(key_len);
if (NULL == key->key)
{
key->key = NULL;
return NULL;
}
memcpy(key->key, str, key_len);
key->hash = DJB2Hash(str);
return key;
}
struct hash_map_str_key* hash_map_str_key_ref(struct hash_map_str_key* key, char* str)
{
ASSERT_MESSAGE((NULL != key), "key 必须由外部保证有效性");
key->key = str;
key->hash = DJB2Hash(str);
return key;
}
hash_map_str_int_entry* hash_map_str_int_entry_new(char* key, int val)
{
struct hash_map_str_int_entry* entry = (struct hash_map_str_int_entry*)malloc(sizeof(struct hash_map_str_int_entry));
if (NULL == entry)
{
return NULL;
}
entry->node.next = NULL;
entry->node.prev = NULL;
if (NULL == hash_map_str_key_init(&(entry->key), key))
{
free(entry);
return NULL;
}
entry->val = val;
return entry;
}
struct hash_trait* hash_map_str_int_trait_init(struct hash_trait* trait)
{
trait->key = hash_map_str_int_entry_key;
trait->hash = hash_map_str_int_entry_hash;
trait->equal = hash_map_str_int_entry_equal;
return trait;
}