8 void htable_init(htable_t
*htable
, size_t size
)
12 /* Allocate memory for `size' tailq headers */
13 if ((htable
->ht_table
= malloc(size
* sizeof *htable
->ht_table
)) == NULL
) {
18 /* Initialize tailqs */
19 for (i
= 0; i
< size
; i
++)
20 TAILQ_INIT(&htable
->ht_table
[i
]);
22 htable
->ht_size
= size
; /* size must be a power of 2 */
26 void htable_insert(htable_t
*htable
, const void *key
, void *data
)
28 struct htablehead
*phead
;
33 hash
= htable
->ht_hashf(key
);
35 /* Search across chain if there is already an entry
36 with the same key. If there is, replace it. */
37 phead
= &htable
->ht_table
[hash
& (htable
->ht_size
- 1)];
38 TAILQ_FOREACH(pnode
, phead
, hn_next
)
39 if (htable
->ht_cmpf(pnode
->hn_key
, key
) == 0) {
40 pnode
->hn_data
= data
;
44 /* Allocate memory for new entry */
45 if ((pnode
= malloc(sizeof *pnode
)) == NULL
)
48 pnode
->hn_data
= data
;
50 TAILQ_INSERT_TAIL(phead
, pnode
, hn_next
);
54 void *htable_search(const htable_t
*htable
, const void *key
)
60 hash
= htable
->ht_hashf(key
);
62 TAILQ_FOREACH(pnode
, &htable
->ht_table
[hash
& (htable
->ht_size
- 1)], hn_next
)
63 if (htable
->ht_cmpf(pnode
->hn_key
, key
) == 0)
64 return pnode
->hn_data
;
69 void htable_print(const htable_t
*htable
)
74 for (i
= 0; i
< htable
->ht_size
; i
++) {
75 TAILQ_FOREACH(pnode
, &htable
->ht_table
[i
], hn_next
)
76 htable
->ht_printf(pnode
->hn_key
, pnode
->hn_data
);
77 if (TAILQ_FIRST(&htable
->ht_table
[i
]) != NULL
)
82 u_int
djb_hash(const void *str
)
87 for (i
= 0; i
< strlen((char*)str
); i
++)
88 hash
= ((hash
<< 5) + hash
) + ((char*)str
)[i
];
90 return (hash
& 0x7FFFFFFF);
93 int mycmp(const void *arg1
, const void *arg2
)
95 return (strcmp((char *) arg1
, (char *) arg2
));
98 void myprintf(const void *key
, const void *data
)
100 printf("%s(%s) ", (char *)key
, (char *)data
);
107 /* Initialize table */
108 htable_init(&ptable
, 10);
110 /* Setup callback functions */
111 ptable
.ht_hashf
= djb_hash
;
112 ptable
.ht_cmpf
= mycmp
;
113 ptable
.ht_printf
= myprintf
;
115 htable_insert(&ptable
, "stathis", "stathis");
116 htable_insert(&ptable
, "maria", "maria");
117 htable_insert(&ptable
, "kostas", "kostas");
118 htable_insert(&ptable
, "panagiotopoulos", "panagiotopoulos");
119 htable_insert(&ptable
, "eleni", "eleni");
121 htable_print(&ptable
);