rework to handle vector variants 0-3
[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(itemkeyfun *this,void *key) {
12     return hashvector_hashcode( key, sizeof( ipslot ) );
13 }
14
15 static void* voidp_itemkey(itemkeyfun *this,void *item) {
16     return item;
17 }
18
19 static int voidp_haskey(itemkeyfun *this,void *item,void *key) {
20     return memcmp( item, key, sizeof( ipslot ) ) == 0;
21 }
22
23 static int shrink(vector *pv,unsigned long index,void *item,void *data) {
24     if ( item ) {
25         if ( item == HV_HOLE ) {
26             ((hashvector*) data)->holes--;
27         } else {
28             free( item );
29             ((hashvector*) data)->fill--;
30         }
31     }
32     return 0;
33 }
34
35 int main(int argc,char **argv) {
36     itemkeyfun voidpfun = {
37         .hashcode = voidp_hashcode,
38         .itemkey = voidp_itemkey,
39         .haskey = voidp_haskey
40     };
41     hashvector hv = {
42         .table = { 4, 0 },
43         .fill = 0,
44         .holes = 0,
45         .type = &voidpfun
46     };
47     int i = 0;
48     for ( ; i < 259; i++ ) {
49         ipslot *item = (ipslot*) calloc( 1, sizeof( ipslot ) );
50         if ( i > 250 ) {
51             int n = i;
52             i = n;
53         }
54         item->family = i;
55         memcpy( item->data, "10.10.10.1", 10 );
56         hashvector_add( &hv, item );
57     }
58     for ( i = 256; i < 260; i++ ) {
59         vector_index index = i;
60         void ** slot = vector_next_used( &hv.table, &index );
61         if ( slot && *slot != HV_HOLE ) {
62             hashvector_delete( &hv, *slot );
63         }
64     }
65     vector_resize( &hv.table, 256, shrink, &hv );
66     return 0;
67 }