portability fixes
[rrq/rrqmisc.git] / tests / example-hashvector.c
1 #include <stdlib.h>
2 #include <string.h>
3 #include "HashVector.h"
4
5 typedef struct _ipslot {
6     int family;
7     unsigned char data[32];
8     unsigned int bits;
9 } ipslot;
10
11 static unsigned long voidp_hashcode(void *this,void *key) {
12     return HashVector_hashcode( key, sizeof( ipslot ) );
13 }
14
15 static void* voidp_itemkey(void *this,void *item) {
16     return item;
17 }
18
19 static int voidp_haskey(void *this,void *item,void *key) {
20     return memcmp( item, key, sizeof( ipslot ) ) == 0;
21 }
22
23 static void voidp_releasekey(void *this,void *key) {
24 }
25
26 static int voidp_tostring(void *this, void *item, char *buffer, int limit) {
27     return snprintf( buffer, limit, "%p", item );
28 }
29
30 static int shrink(Vector *pv,unsigned long index,void *item,void *data) {
31     if ( item ) {
32         if ( item == HV_HOLE ) {
33             ((HashVector*) data)->holes--;
34         } else {
35             free( item );
36             ((HashVector*) data)->fill--;
37         }
38     }
39     return 0;
40 }
41
42 int main(int argc,char **argv) {
43     ItemKeyFun voidpfun = {
44         .hashcode = voidp_hashcode,
45         .itemkey = voidp_itemkey,
46         .haskey = voidp_haskey,
47         .releasekey = voidp_releasekey,
48         .tostring = voidp_tostring
49     };
50     HashVector hv = {
51         .table = { 1, 4, 0 },
52         .fill = 0,
53         .holes = 0,
54         .type = &voidpfun
55     };
56     int i = 0;
57     for ( ; i < 259; i++ ) {
58         ipslot *item = (ipslot*) calloc( 1, sizeof( ipslot ) );
59         if ( i > 250 ) {
60             int n = i;
61             i = n;
62         }
63         item->family = i;
64         memcpy( item->data, "10.10.10.1", 10 );
65         HashVector_add( &hv, item );
66     }
67     for ( i = 256; i < 260; i++ ) {
68         VectorIndex index = i;
69         void ** slot = Vector_next_used( &hv.table, &index );
70         if ( slot && *slot != HV_HOLE ) {
71             HashVector_delete( &hv, *slot );
72         }
73     }
74     Vector_resize( &hv.table, 256, shrink, &hv );
75     return 0;
76 }