-
Notifications
You must be signed in to change notification settings - Fork 0
/
nhash.c
124 lines (110 loc) · 2.5 KB
/
nhash.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
124
#include "nhash.h"
int nhash_init_table(nhash_table *table, uint32_t size)
{
int i;
uint32_t mask = 0;
for (i =1; i< 32; i++)
{
mask = ((mask<<1) + 1);
if ((size >> i)==0)
{
break;
}
}
table->array_mask = mask;
table->table_size = mask+1; /* We cant have arbitary size tables */
table->bucket = malloc (sizeof(bucket_entry)*(mask+1));
if(table->bucket == NULL)
{
fprintf(stderr, "nhash_init_table: Malloc failed!\n");
exit(1);
}
memset(table->bucket, 0, sizeof(bucket_entry)*(mask+1));
return 0;
}
int nhash_insert_key(nhash_table *table, n_key_val *nodeptr)
{
uint32_t arr_index;
// uint64_t key,val;
bucket_entry *bucket=NULL;
n_key_val *temp = NULL;
int i;
// key = kv->key;
// val = kv->val;
arr_index = ((uint32_t)table->array_mask & nodeptr->key);
bucket = &table->bucket[arr_index];
if (bucket->max_entries == 0)
{
bucket->key_val = malloc(sizeof (n_key_val) * 10);
bucket->max_entries = 10;
}
else if (bucket->max_entries == bucket->used_entries)
{
temp = malloc(sizeof(n_key_val) * ( bucket->max_entries+10));
memcpy(temp,bucket->key_val, sizeof(n_key_val)*(bucket->max_entries));
free(bucket->key_val);
bucket->key_val = temp;
bucket->max_entries +=10;
}
i = bucket->used_entries;
bucket->key_val[i] = *nodeptr;
/*
bucket->key_val[i].key = key;
bucket->key_val[i].val = val;*/
bucket->used_entries++;
return 0;
}
int nhash_delete_key(nhash_table *table, uint64_t key)
{
int deleted=0;
uint32_t arr_index;
bucket_entry *bucket=NULL;
int i,j;
arr_index = (table->array_mask & key);
bucket = &table->bucket[arr_index];
if (bucket->max_entries == 0)
{
return 1; /* Key not found */
}
else
{
for(i=0;i<bucket->used_entries; i++)
{
if (key == bucket->key_val[i].key)
{
for (j=i+1;j<bucket->used_entries;j++)
{
bucket->key_val[j-1] = bucket->key_val[j];
}
bucket->used_entries--;
deleted = 1;
break;
}
}
}
if (deleted)
return 0;
else
return 1;
}
n_key_val * nhash_search_key(nhash_table *table, uint64_t key)
{
int i;
uint32_t arr_index;
bucket_entry *bucket=NULL;
arr_index = ((uint32_t)table->array_mask & key);
bucket = &table->bucket[arr_index];
if (bucket->max_entries)
{
for(i=0;i<bucket->used_entries; i++)
{
if (key == bucket->key_val[i].key)
{
return &bucket->key_val[i];
}
}
}
else
return NULL;
return NULL;
}