Merge branch 'exp-hash'
[eleutheria.git] / genstructs / htable / main.c
blob898edaa48e7d95e9285687cddda34aa6c03baaf7
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
5 #include "htable.h"
7 unsigned int djb_hash(const void *key)
9 unsigned int i, hash = 5381;
10 char *str = (char *)key;
12 for (i = 0; i < strlen(str); i++)
13 hash = ((hash << 5) + hash) + str[i];
15 return (hash & 0x7FFFFFFF);
18 int mystrcmp(const void *arg1, const void *arg2)
20 return (strcmp((char *) arg1, (char *) arg2));
23 void myprintf(const void *key, const void *data)
25 printf("%s(%s) ", (char *)key, (char *)data);
28 void print_elm(void *data)
30 printf("%s\n", (char *)data);
33 int main(void)
35 htable_t htable;
36 char *p = malloc(100);
37 char *s = malloc(100);
38 char *t = malloc(100);
39 char *q = malloc(100);
41 strcpy(p, "stathis");
42 strcpy(s, "maria");
43 strcpy(t, "kostas");
44 strcpy(q, "eleni");
46 /* Initialize table */
47 if (htable_init(&htable, 1, 1, djb_hash, mystrcmp, myprintf) == HT_NOMEM) {
48 perror("malloc");
49 exit(EXIT_FAILURE);
52 htable_insert(&htable, "stathis", p);
53 htable_insert(&htable, "maria", s);
54 htable_insert(&htable, "kostas", t);
55 htable_insert(&htable, "eleni", q);
56 htable_print(&htable);
58 htable_traverse(&htable, print_elm);
60 /* Free memory */
61 htable_free_all_obj(&htable, HT_FREEDATA);
62 htable_free(&htable);
64 return EXIT_SUCCESS;