Separate netbsd-specific from unix-specific projects
[eleutheria.git] / netbsd / genstructs / htable / test1.c
blobd8b5dab4f0edfd267de6d073f2f6a4f766cdbb05
1 /*
2 * Compile with:
3 * gcc test1.c htable.c -o test1 -Wall -W -Wextra -ansi -pedantic
5 */
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <time.h> /* for time() in srand() */
12 #include "htable.h"
14 /* Function prototypes */
15 unsigned int myhashf(const void *key);
16 int mystrcmp(const void *arg1, const void *arg2);
17 void myprintf(const void *key, const void *data);
18 void print_elm(void *data);
19 void get_rand_string(char *str, size_t len);
21 int main(void)
23 htable_t htable;
24 size_t i;
25 char str[20][10+1]; /* +1 for '\0' */
27 /* Initialize random number generator */
28 srand(time(NULL));
30 /* Produce some random strings to put in hash table */
31 for (i = 0; i < sizeof str / sizeof *str; i++)
32 get_rand_string(str[i], 10);
34 /* Initialize table */
35 if (htable_init(&htable, 32, 2, myhashf, mystrcmp, myprintf) == HT_NOMEM) {
36 perror("malloc");
37 exit(EXIT_FAILURE);
40 /* Add random entries in hash table */
41 for (i = 0; i < sizeof str / sizeof *str; i++)
42 htable_insert(&htable, str[i], str[i]);
43 /* htable_print(&htable); */
46 * Traverse all elemets and print each one of them
47 * using the print_elm() callback function
49 htable_traverse(&htable, print_elm);
52 * Print the length of every chain
53 * This gives as a metric on how good or bad our hash function is
55 for (i = 0; i < htable_get_size(&htable); i++)
56 printf("chain[%lu] = %lu\n",
57 (unsigned long)i,
58 (unsigned long)htable_stat_get_chain_len(&htable, i));
60 /* Print number of automatic resizes */
61 printf("Automatic resizes: %lu\n", (unsigned long)htable_stat_get_grows(&htable));
63 /* Free memory */
64 htable_free(&htable);
66 return EXIT_SUCCESS;
69 unsigned int myhashf(const void *key)
71 unsigned int i, hash = 5381;
72 char *str = (char *)key;
74 for (i = 0; i < strlen(str); i++)
75 hash = ((hash << 5) + hash) + str[i];
77 return hash;
80 int mystrcmp(const void *arg1, const void *arg2)
82 return (strcmp((char *)arg1, (char *)arg2));
85 void myprintf(const void *key, const void *data)
87 printf("%s(%s) ", (char *)key, (char *)data);
90 void print_elm(void *data)
92 printf("%s\n", (char *)data);
95 void get_rand_string(char *str, size_t len)
97 size_t i;
99 for (i = 0; i < len; i++)
100 str[i] = 65 + 32 + (rand() / (RAND_MAX / 26 + 1)); /* 'a' to 'z' */
101 str[i] = '\0';