1 /* Copyright (c) 2006-2009, Stig Venaas, UNINETT AS.
2 * Copyright (c) 2010, UNINETT AS, NORDUnet A/S.
3 * Copyright (c) 2010-2012, NORDUnet A/S. */
4 /* See LICENSE for licensing information. */
12 /* allocates and initialises hash structure; returns NULL if malloc fails */
13 struct hash *hash_create() {
14 struct hash *h = malloc(sizeof(struct hash));
17 h->hashlist = list_create();
22 pthread_mutex_init(&h->mutex, NULL);
26 /* frees all memory associated with the hash */
27 void hash_destroy(struct hash *h) {
32 for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
33 free(((struct hash_entry *)ln->data)->key);
34 free(((struct hash_entry *)ln->data)->data);
36 list_destroy(h->hashlist);
37 pthread_mutex_destroy(&h->mutex);
40 /* insert entry in hash; returns 1 if ok, 0 if malloc fails */
41 int hash_insert(struct hash *h, void *key, uint32_t keylen, void *data) {
46 e = malloc(sizeof(struct hash_entry));
49 memset(e, 0, sizeof(struct hash_entry));
50 e->key = malloc(keylen);
55 memcpy(e->key, key, keylen);
58 pthread_mutex_lock(&h->mutex);
59 if (!list_push(h->hashlist, e)) {
60 pthread_mutex_unlock(&h->mutex);
65 pthread_mutex_unlock(&h->mutex);
69 /* reads entry from hash */
70 void *hash_read(struct hash *h, void *key, uint32_t keylen) {
76 pthread_mutex_lock(&h->mutex);
77 for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
78 e = (struct hash_entry *)ln->data;
79 if (e->keylen == keylen && !memcmp(e->key, key, keylen)) {
80 pthread_mutex_unlock(&h->mutex);
84 pthread_mutex_unlock(&h->mutex);
88 /* extracts entry from hash */
89 void *hash_extract(struct hash *h, void *key, uint32_t keylen) {
95 pthread_mutex_lock(&h->mutex);
96 for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
97 e = (struct hash_entry *)ln->data;
98 if (e->keylen == keylen && !memcmp(e->key, key, keylen)) {
100 list_removedata(h->hashlist, e);
102 pthread_mutex_unlock(&h->mutex);
106 pthread_mutex_unlock(&h->mutex);
110 /* returns first entry */
111 struct hash_entry *hash_first(struct hash *hash) {
112 struct list_node *ln;
113 struct hash_entry *e;
114 if (!hash || !((ln = list_first(hash->hashlist))))
116 e = (struct hash_entry *)ln->data;
121 /* returns the next node after the argument */
122 struct hash_entry *hash_next(struct hash_entry *entry) {
123 struct hash_entry *e;
124 if (!entry || !entry->next)
126 e = (struct hash_entry *)entry->next->data;
127 e->next = (struct list_node *)entry->next->next;
131 /* Local Variables: */
132 /* c-file-style: "stroustrup" */