added
[rrq/rrqmisc.git] / htable / example-htable.c
1 /**
2  * This is an example of using htable.
3  */
4 #include <stddef.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include "htable.h"
9
10 /**
11  * This is a table item, which is keyed on a 16-byte value.
12  */
13 struct Counter {
14     int value;
15     char key[16];
16     void *unused;
17 };
18
19 /**
20  * Hash function for the Counter keys. Note that this is an
21  * illsutration example only and there is no analysis of it being
22  * useful.
23  */
24 static int Counter_hashcode( struct _htable *table, unsigned char *key ) {
25     int value = 0;
26     int i = 16;
27     unsigned char *end = key + 16;
28     unsigned char *p = key;
29     while ( p != end ) {
30         value += *(p++) + (i--);
31     }
32     return value;
33 }
34
35 /**
36  * A hash table of Counter records using Counter_hashcode
37  */
38 static htable counters = HTABLEINIT( struct Counter, key, Counter_hashcode );
39
40 #define MIN( a, b ) ({ int ax = a, bx = b; ( ax < bx )? ax : bx; })
41
42 /**
43  * setup a temporary struct Counter, and return a usefully cast
44  * pointer.
45  */
46 static struct Counter *Counter_create(char *key) {
47     struct Counter *counter = (struct Counter *)
48         calloc( 1, sizeof( struct Counter ) );
49     memcpy( counter->key, key, MIN( strlen( key ), sizeof( counter->key ) ) );
50     return counter;
51 }
52
53 static void Counter_dumpitem(int i,unsigned char *itemp) {
54     struct Counter *item = (struct Counter *) itemp;
55     fprintf(stdout, "[%03d] %16s %d %p\n",
56             i, item->key, item->value, item->unused );
57 }
58
59 int main(int argc,char **argv) {
60     static char *keys[] = {
61         "something", "intro", "foo bar", "hexadecimal", "burp", 0 };
62
63     int i;
64     for ( i = 0; keys[ i ]; i++ ) {
65         struct Counter *item = Counter_create( keys[ i ] );
66         item->unused = item;
67         item->value = i;
68         htadd( &counters, (unsigned char *)item );
69     }
70     fprintf( stdout, "table size = %d\n", counters.size );
71     htdump( &counters, Counter_dumpitem );
72     return 0;
73 }