]>
git.datanom.net - hashtable.git/blob - hashtable.c
f5569fb8a5f15953a9efd82895e300a782a1374e
11 typedef struct _Hashtable
{
18 static uint32_t hash_table_index(Hashtable
* ht
, const void* key
) {
19 return (ht
->hash(key
) % ht
->size
);
22 Hashtable
* hash_table_create(HashFunc hf
, EqualFunc ef
) {
23 return hash_table_create_full(hf
, ef
, TABLESIZE
);
26 Hashtable
* hash_table_create_full(HashFunc hf
, EqualFunc ef
, uint32_t size
) {
27 Hashtable
* ht
= malloc(sizeof(*ht
));
31 ht
->sets
= calloc(sizeof(Set
*), ht
->size
);
35 void hash_table_destroy(Hashtable
* ht
) {
36 for (uint32_t i
= 0; i
< ht
->size
; i
++) {
37 if (ht
->sets
[i
] != NULL
) {
38 Set
* tmp
= ht
->sets
[i
];
52 void hash_table_print(Hashtable
* ht
) {
53 printf("Start Table\n");
54 for (uint32_t i
= 0; i
< ht
->size
; i
++) {
55 if (ht
->sets
[i
] == NULL
) {
56 //printf("\t%i\t---\n", i);
58 printf("\t%i\t\n", i
);
59 Set
* tmp
= ht
->sets
[i
];
61 printf("\"%ju\" - (%p)", tmp
->key
, tmp
->data
);
66 printf("End Table\n");
69 bool hash_table_insert(Hashtable
* ht
, const void* key
, void* obj
) {
70 if (key
== NULL
|| obj
== NULL
|| ht
== NULL
) return false;
73 void* found
= hash_table_lookup(ht
, key
);
75 printf("[%s:%s] - %s: Missing chaining\n", (const char*) found
, (const char*) key
, (const char*) obj
);
79 uint32_t index
= hash_table_index(ht
, key
);
81 Set
* set
= malloc(sizeof(*set
));
85 ht
->sets
[index
] = set
;
89 void* hash_table_lookup(Hashtable
* ht
, const void* key
) {
90 if (key
== NULL
|| ht
== NULL
) return false;
91 uint64_t index
= hash_table_index(ht
, key
);
93 Set
* set
= ht
->sets
[index
];
94 if (set
== NULL
) return NULL
;
95 //printf("find: %p -> found: %p\n", key, set->data);
97 if (ht
->compare(set
->data
, key
))
103 void* hash_table_delete(Hashtable
* ht
, const void* key
) {
104 if (key
== NULL
|| ht
== NULL
) return false;
105 uint64_t index
= hash_table_index(ht
, key
);
107 Set
* tmp
= ht
->sets
[index
];
108 if (tmp
!= NULL
&& ht
->compare((void*)tmp
->key
, (void*)index
) == false) return NULL
;
110 if (tmp
== NULL
) return NULL
;
112 void* result
= tmp
->data
;
117 uint64_t int_hash(const void* key
) {
118 return *(uint64_t*) key
;
121 uint64_t str_hash(const void* key
) {
122 const signed char* p
;
125 for (p
= key
; *p
!= '\0'; p
++) {
126 h
= (h
<< 5) + h
+ *p
;
132 uint64_t ptr_hash(const void* key
) {
133 return (uint64_t)key
;
136 bool int_equal(const void* a
, const void* b
) {
137 return *((const int*) a
) == *((const int*) b
);
140 bool str_equal(const void* a
, const void* b
) {
141 const char *string1
= (const char*) a
;
142 const char *string2
= (const char*) b
;
144 return strcmp (string1
, string2
) == 0;
147 bool ptr_equal(const void* a
, const void* b
) {
This page took 0.113361 seconds and 4 git commands to generate.