1 /* Copyright (c) 2006-2010, UNINETT AS
2 * Copyright (c) 2010-2012, NORDUnet A/S */
3 /* See LICENSE for licensing information. */
11 /* allocates and initialises hash structure; returns NULL if malloc fails */
12 struct hash *hash_create() {
13 struct hash *h = malloc(sizeof(struct hash));
16 h->hashlist = list_create();
21 pthread_mutex_init(&h->mutex, NULL);
25 /* frees all memory associated with the hash */
26 void hash_destroy(struct hash *h) {
31 for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
32 free(((struct hash_entry *)ln->data)->key);
33 free(((struct hash_entry *)ln->data)->data);
35 list_destroy(h->hashlist);
36 pthread_mutex_destroy(&h->mutex);
39 /* insert entry in hash; returns 1 if ok, 0 if malloc fails */
40 int hash_insert(struct hash *h, void *key, uint32_t keylen, void *data) {
45 e = malloc(sizeof(struct hash_entry));
48 memset(e, 0, sizeof(struct hash_entry));
49 e->key = malloc(keylen);
54 memcpy(e->key, key, keylen);
57 pthread_mutex_lock(&h->mutex);
58 if (!list_push(h->hashlist, e)) {
59 pthread_mutex_unlock(&h->mutex);
64 pthread_mutex_unlock(&h->mutex);
68 /* reads entry from hash */
69 void *hash_read(struct hash *h, void *key, uint32_t keylen) {
75 pthread_mutex_lock(&h->mutex);
76 for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
77 e = (struct hash_entry *)ln->data;
78 if (e->keylen == keylen && !memcmp(e->key, key, keylen)) {
79 pthread_mutex_unlock(&h->mutex);
83 pthread_mutex_unlock(&h->mutex);
87 /* extracts entry from hash */
88 void *hash_extract(struct hash *h, void *key, uint32_t keylen) {
94 pthread_mutex_lock(&h->mutex);
95 for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
96 e = (struct hash_entry *)ln->data;
97 if (e->keylen == keylen && !memcmp(e->key, key, keylen)) {
99 list_removedata(h->hashlist, e);
101 pthread_mutex_unlock(&h->mutex);
105 pthread_mutex_unlock(&h->mutex);
109 /* returns first entry */
110 struct hash_entry *hash_first(struct hash *hash) {
111 struct list_node *ln;
112 struct hash_entry *e;
113 if (!hash || !((ln = list_first(hash->hashlist))))
115 e = (struct hash_entry *)ln->data;
120 /* returns the next node after the argument */
121 struct hash_entry *hash_next(struct hash_entry *entry) {
122 struct hash_entry *e;
123 if (!entry || !entry->next)
125 e = (struct hash_entry *)entry->next->data;
126 e->next = (struct list_node *)entry->next->next;
130 /* Local Variables: */
131 /* c-file-style: "stroustrup" */