00001 #include "hashmap.h"
00002 #include "dbug_mem.h"
00003
00004
00005 int
00006 chtbl_init(CHTbl *htbl, int buckets, int (*h)(const void *key), int
00007 (*match)(const void *obj1, const void *obj2), void (*destroy)(void *obj))
00008 {
00009 int i;
00010
00011
00012
00013 T_RDWR_INIT(&(htbl->rwlock), NULL);
00014
00015
00016 if ((htbl->table = (List *)malloc(buckets * sizeof(List))) == NULL)
00017 return -1;
00018
00019
00020 htbl->buckets = buckets;
00021
00022 for (i = 0; i < htbl->buckets; i++) {
00023 list_init(&htbl->table[i], match, destroy);
00024 }
00025
00026
00027 htbl->h = h;
00028
00029 return 0;
00030 }
00031
00032
00033 void
00034 chtbl_destroy(CHTbl *htbl)
00035 {
00036 int i;
00037
00038
00039
00040 T_RDWR_WLOCK(&(htbl->rwlock));
00041
00042
00043 for (i = 0; i < htbl->buckets; i++) {
00044 list_destroy(&htbl->table[i]);
00045 }
00046
00047
00048 free(htbl->table);
00049
00050
00051 memset(htbl, 0, sizeof(CHTbl));
00052
00053 T_RDWR_WUNLOCK(&(htbl->rwlock));
00054
00055 return;
00056 }
00057
00058
00059 int
00060 chtbl_size(CHTbl *htbl)
00061 {
00062 int cnt = 0;
00063 int i;
00064
00065
00066
00067 T_RDWR_RLOCK(&(htbl->rwlock));
00068
00069 for (i = 0; i < htbl->buckets; i++) {
00070 cnt += list_getsize(&htbl->table[i]);
00071 }
00072
00073 T_RDWR_RUNLOCK(&(htbl->rwlock));
00074
00075 return cnt;
00076 }
00077
00078
00079 int
00080 chtbl_insert(CHTbl *htbl, const void *data)
00081 {
00082 void *temp;
00083 int bucket, retval;
00084
00085
00086
00087
00088
00089 temp = (void *)data;
00090
00091 T_RDWR_RLOCK(&(htbl->rwlock));
00092
00093
00094 bucket = htbl->h(data) % htbl->buckets;
00095
00096
00097 retval = list_insert(&htbl->table[bucket], (void *)data);
00098
00099 T_RDWR_RUNLOCK(&(htbl->rwlock));
00100
00101 return retval;
00102 }
00103
00104
00105 int
00106 chtbl_remove(CHTbl *htbl, void **data)
00107 {
00108 int bucket;
00109 int retval = -1;
00110
00111
00112
00113 T_RDWR_RLOCK(&(htbl->rwlock));
00114
00115
00116 bucket = htbl->h(*data) % htbl->buckets;
00117
00118
00119 retval = list_remove(&htbl->table[bucket], data);
00120
00121 T_RDWR_RUNLOCK(&(htbl->rwlock));
00122
00123
00124 return retval;
00125 }
00126
00127
00128 int
00129 chtbl_lookup(CHTbl *htbl, void **data)
00130 {
00131 int bucket = 0;
00132 int retval = 0;
00133
00134
00135
00136 T_RDWR_RLOCK(&(htbl->rwlock));
00137
00138
00139 bucket = htbl->h(*data) % htbl->buckets;
00140
00141 retval = list_lookup(&(htbl->table[bucket]), data);
00142
00143 T_RDWR_RUNLOCK(&(htbl->rwlock));
00144
00145 return retval;
00146 }