2 * Copyright (C) 2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
15 /* allocates and initialises hash structure; returns NULL if malloc fails */
16 struct hash *hash_create() {
17 struct hash *h = malloc(sizeof(struct hash));
20 h->hashlist = list_create();
25 pthread_mutex_init(&h->mutex, NULL);
29 /* frees all memory associated with the hash */
30 void hash_destroy(struct hash *h) {
35 for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
36 free(((struct hash_entry *)ln->data)->key);
37 free(((struct hash_entry *)ln->data)->data);
39 list_destroy(h->hashlist);
40 pthread_mutex_destroy(&h->mutex);
43 /* insert entry in hash; returns 1 if ok, 0 if malloc fails */
44 int hash_insert(struct hash *h, void *key, uint32_t keylen, void *data) {
49 e = malloc(sizeof(struct hash_entry));
52 memset(e, 0, sizeof(struct hash_entry));
53 e->key = malloc(keylen);
58 memcpy(e->key, key, keylen);
61 pthread_mutex_lock(&h->mutex);
62 if (!list_push(h->hashlist, e)) {
63 pthread_mutex_unlock(&h->mutex);
68 pthread_mutex_unlock(&h->mutex);
72 /* reads entry from hash */
73 void *hash_read(struct hash *h, void *key, uint32_t keylen) {
79 pthread_mutex_lock(&h->mutex);
80 for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
81 e = (struct hash_entry *)ln->data;
82 if (e->keylen == keylen && !memcmp(e->key, key, keylen)) {
83 pthread_mutex_unlock(&h->mutex);
87 pthread_mutex_unlock(&h->mutex);
91 /* extracts entry from hash */
92 void *hash_extract(struct hash *h, void *key, uint32_t keylen) {
98 pthread_mutex_lock(&h->mutex);
99 for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
100 e = (struct hash_entry *)ln->data;
101 if (e->keylen == keylen && !memcmp(e->key, key, keylen)) {
103 list_removedata(h->hashlist, e);
105 pthread_mutex_unlock(&h->mutex);
109 pthread_mutex_unlock(&h->mutex);
113 /* returns first entry */
114 struct hash_entry *hash_first(struct hash *hash) {
115 struct list_node *ln;
116 struct hash_entry *e;
117 if (!hash || !((ln = list_first(hash->hashlist))))
119 e = (struct hash_entry *)ln->data;
124 /* returns the next node after the argument */
125 struct hash_entry *hash_next(struct hash_entry *entry) {
126 struct hash_entry *e;
127 if (!entry || !entry->next)
129 e = (struct hash_entry *)entry->next->data;
130 e->next = (struct list_node *)entry->next->next;
134 /* Local Variables: */
135 /* c-file-style: "stroustrup" */