Build up a more robust test case
[eleutheria.git] / genstructs / htable / main.c
blob00081e5409002cc3c6fa10715908c349a35ee47f
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <time.h> /* for time() in srand() */
6 #include "htable.h"
8 unsigned int myhashf(const void *key)
10 unsigned int i, hash = 5381;
11 char *str = (char *)key;
13 for (i = 0; i < strlen(str); i++)
14 hash = ((hash << 5) + hash) + str[i];
16 return hash;
19 int mystrcmp(const void *arg1, const void *arg2)
21 return (strcmp((char *)arg1, (char *)arg2));
24 void myprintf(const void *key, const void *data)
26 printf("%s(%s) ", (char *)key, (char *)data);
29 void print_elm(void *data)
31 printf("%s\n", (char *)data);
34 void get_rand_string(char *str, size_t len)
36 size_t i;
38 for (i = 0; i < len; i++)
39 str[i] = 32 + 65 + (rand() / (RAND_MAX / 26 + 1));
40 str[i] = '\0';
43 int main(void)
45 htable_t htable;
46 size_t i;
47 char str[20][10+1]; /* +1 for '\0' */
49 /* Initialize random number generator */
50 srand(time(NULL));
52 for (i = 0; i < sizeof str / sizeof *str; i++)
53 get_rand_string(str[i], 10);
55 /* Initialize table */
56 if (htable_init(&htable, 32, 2, myhashf, mystrcmp, myprintf) == HT_NOMEM) {
57 perror("malloc");
58 exit(EXIT_FAILURE);
61 /* Add random entries in hash table */
62 for (i = 0; i < sizeof str / sizeof *str; i++)
63 htable_insert(&htable, str[i], str[i]);
64 /* htable_print(&htable); */
66 /* Traverse all elemets and print each one of them */
67 htable_traverse(&htable, print_elm);
69 /* Print the length of every chain */
70 for (i = 0; i < htable_get_size(&htable); i++)
71 printf("chain[%lu] = %lu\n",
72 (unsigned long)i,
73 (unsigned long)htable_stat_get_chain_len(&htable, i));
75 /* Print number of automatic resizes */
76 printf("Automatic resizes: %lu\n", (unsigned long)htable_stat_get_grows(&htable));
78 /* Free memory */
79 htable_free(&htable);
81 return EXIT_SUCCESS;