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.
21 /* allocates and initialises hash structure; returns NULL if malloc fails */
22 struct hash *hash_create() {
23 struct hash *h = malloc(sizeof(struct hash));
26 h->hashlist = list_create();
31 pthread_mutex_init(&h->mutex, NULL);
35 /* frees all memory associated with the hash */
36 void hash_destroy(struct hash *h) {
41 for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
42 free(((struct entry *)ln->data)->key);
43 free(((struct entry *)ln->data)->data);
45 list_destroy(h->hashlist);
46 pthread_mutex_destroy(&h->mutex);
49 /* insert entry in hash; returns 1 if ok, 0 if malloc fails */
50 int hash_insert(struct hash *h, void *key, uint32_t keylen, void *data) {
55 e = malloc(sizeof(struct entry));
58 e->key = malloc(keylen);
63 memcpy(e->key, key, keylen);
66 pthread_mutex_lock(&h->mutex);
67 if (!list_push(h->hashlist, e)) {
68 pthread_mutex_unlock(&h->mutex);
73 pthread_mutex_unlock(&h->mutex);
77 /* reads entry from hash */
78 void *hash_read(struct hash *h, void *key, uint32_t keylen) {
84 pthread_mutex_lock(&h->mutex);
85 for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
86 e = (struct entry *)ln->data;
87 if (e->keylen == keylen && !memcmp(e->key, key, keylen)) {
88 pthread_mutex_unlock(&h->mutex);
92 pthread_mutex_unlock(&h->mutex);