Repository navigation
Expand file tree
/
Copy pathhashTable.c
More file actions
143 lines (104 loc) · 2.83 KB
/
Copy pathhashTable.c
File metadata and controls
143 lines (104 loc) · 2.83 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
HashTable* hash_table_create(DataDestroyFunc data_destroy, void* ctx, DataHashFunc hash, int slot_nr
)
{
HashTable* thiz = NULL;
return_val_if_fail(hash != NULL && slot_nr > 1, NULL);
thiz = (HashTable*)malloc(sizeof(HashTable));
if(thiz != NULL)
{
thiz->hash = hash;
thiz->slot_nr = slot_nr;
thiz->data_destroy_ctx = ctx;
thiz->data_destroy = data_destroy;
if((thiz->slots = (DList**)calloc(sizeof(DList*)*slot_nr, 1)) == NULL)
{
free(thiz);
thiz = NULL;
}
}
return thiz;
}
Ret hash_table_insert(HashTable* thiz, void* data)
{
size_t index = 0;
return_val_if_fail(thiz != NULL, RET_INVALID_PARAMS);
index = thiz->hash(data)%thiz->slot_nr;
if(thiz->slots[index] == NULL)
{
thiz->slots[index] = dlist_create(thiz->data_destroy, thiz->data_destroy_ctx);
}
return dlist_prepend(thiz->slots[index], data);
}
Ret hash_table_delete(HashTable* thiz, DataCompareFunc cmp, void* data)
{
int index = 0;
DList* dlist = NULL;
return_val_if_fail(thiz != NULL && cmp != NULL, RET_INVALID_PARAMS);
index = thiz->hash(data)%thiz->slot_nr;
dlist = thiz->slots[index];
if(dlist != NULL)
{
index = dlist_find(dlist, cmp, data);
return dlist_delete(dlist, index);
}
return RET_FAIL;
}
Ret hash_table_find(HashTable* thiz, DataCompareFunc cmp, void* data, void** ret_data)
{
int index = 0;
DList* dlist = NULL;
return_val_if_fail(thiz != NULL && cmp != NULL && ret_data != NULL, RET_INVALID_PARAMS);
index = thiz->hash(data)%thiz->slot_nr;
dlist = thiz->slots[index];
if(dlist != NULL)
{
index = dlist_find(dlist, cmp, data);
return dlist_get_by_index(dlist, index, ret_data);
}
return RET_FAIL;
}
size_t hash_table_length(HashTable* thiz)
{
size_t i = 0;
size_t nr = 0;
return_val_if_fail(thiz != NULL, 0);
for(i = 0; i < thiz->slot_nr; i++)
{
if(thiz->slots[i] != NULL)
{
nr += dlist_length(thiz->slots[i]);
}
}
return nr;
}
Ret hash_table_foreach(HashTable* thiz, DataVisitFunc visit, void* ctx)
{
size_t i = 0;
return_val_if_fail(thiz != NULL && visit != NULL, RET_INVALID_PARAMS);
for(i = 0; i < thiz->slot_nr; i++)
{
if(thiz->slots[i] != NULL)
{
dlist_foreach(thiz->slots[i], visit, ctx);
}
}
return RET_OK;
}
void hash_table_destroy(HashTable* thiz)
{
size_t i = 0;
if(thiz != NULL)
{
for(i = 0; i < thiz->slot_nr; i++)
{
if(thiz->slots[i] != NULL)
{
dlist_destroy(thiz->slots[i]);
thiz->slots[i] = NULL;
}
}
free(thiz->slots);
free(thiz);
}
return;
}